Types and values

Type conversions

Choose among three operations:

  • as(kind) checks the current zval type and reads it without conversion.
  • cast(kind) returns the result of a PHP explicit cast and preserves the source zval.
  • convert(kind) applies a PHP explicit cast in place.

Both cast and convert support .int, .float, .bool, .str, .array and .object. cast(.str) returns an owned Zend string. convert(.str) borrows the resulting Zend string and convert(.string) borrows its bytes. cast does not support .string.

OperationEffect on sourceResult ownership
as(kind)Checks the type onlyCopies scalars and borrows slices or wrappers
cast(kind)Preserves the valueCaller owns .str, .array and .object results
convert(kind)Replaces the valueBorrows from the converted zval for pointer and slice results

Casting without modifying the source

const args = try ctx.call.expectArgs(&.{.{ .mixed = .{} }}, {});
const text = try args[0].cast(.str);
defer text.release();
ctx.ret(.string, text.slice());

cast(.str) returns a *zend.String. Borrow its bytes with slice(). Release or transfer converted strings, arrays and objects. Scalars need no release. cast preserves the source zval, but arrays and objects may still share underlying data.

Convert in place

const args = try ctx.call.expectArgs(&.{.{ .mixed = .{} }}, {});
phpz.Zval.raw.copy(ctx.retval.ptr(), args[0].ptr());
_ = try ctx.retval.convert(.int);

Copy the input into the zval at ctx.retval before converting the copy in place. convert unwraps the reference and leaves other reference owners with their original value. A borrowed slice or object pointer is invalidated when the converted zval changes or is released.

After a failed convert, the source may already have changed. A failed cast preserves it. Both operations can invoke object handlers and raise PHP exceptions. Only convert actual PHP values. Internal states such as undef and indirect are unsuitable.

Target types

Targetcast resultconvert result
.inti64i64
.floatf64f64
.boolboolbool
.strOwned *zend.StringBorrowed *zend.String
.stringUnsupportedBorrowed []const u8
.arrayOwned *zend.ArrayBorrowed *zend.Array
.objectOwned *zend.ObjectBorrowed *zend.Object