Class Properties
This chapter covers how to define a class property.
Code sample for this chapter, with additional examples, is available here.
Userland PHP Code Snippet
The code below shows how a class property would be declared in userland PHP code.
class Hdi {
public int $value;
}
Internal PHP Code
The following sections show all required code to declare and implement a class property internally in PHP.
PHP Stub (hdi.stub.php
)
The stub file may or may not declare class properties, but the stub generator script (gen_stub.php) will not produce any output related to them as they are implementation specific.
Argument Information (hdi_arginfo.h
)
Class properties are not referred to nor registered in the argument information file, so it can be skipped.
Implementation (hdi.c
)
zend_string *propName = zend_string_init("value", sizeof("value") - 1, false);
zval propDefaultValue;
/* default property value (undefined) */
ZVAL_UNDEF(&propDefaultValue);
zend_declare_typed_property(
classEntry,
propName,
&defaultValue,
ZEND_ACC_PRIVATE,
NULL,
(zend_type)ZEND_TYPE_INIT_MASK(MAY_BE_LONG)
);
zend_string_release(propName);
Macros and Functions:
Visibility options:
Type options:
- MAY_BE_NULL
- MAY_BE_BOOL
- MAY_BE_LONG
- MAY_BE_DOUBLE
- MAY_BE_STRING
- MAY_BE_ARRAY
- MAY_BE_OBJECT
- MAY_BE_RESOURCE
- MAY_BE_ANY
- MAY_BE_REF
Manipulating Property Values
Update/Set a Property
Updating a property value is straight forward:
- update function (
zend_update_property_long
)- class entry (
classEntry
) - object reference (
Z_OBJ_P(ZEND_THIS)
ie.$this
) - property name string (
"value"
) - property name size (
sizeof
) - value (
42
)
- class entry (
zend_update_property_long(
classEntry,
Z_OBJ_P(ZEND_THIS),
"value",
sizeof("value") - 1,
42
);
Note that for static properties,
zend_update_property_long
must be replaced by its static version (zend_update_static_property_long
), that does not have an object argument.
Macros and Functions:
Read a Property
Reading a property value requires a bit more leg work:
- read function (
zend_read_property
)- class entry (
classEntry
) - object reference (
Z_OBJ_P(ZEND_THIS)
ie.$this
) - property name string (
"value"
) - property name size (
sizeof
) - ???
- ???
- class entry (
zval rv;
zval *value = zend_read_property(
classEntry,
Z_OBJ_P(ZEND_THIS),
"value",
sizeof("value") - 1,
true,
&rv
);
Note that for static properties,
zend_read_property
must be replaced by its static version (zend_read_static_property
), that does not have an object argument.
Macros and Functions:
Copyright (c) 2022 - Flavio Heleno