How to add an array as a property of an object to a class declared in a PHP extension?

I want my PHP extension to declare a class equivalent to the following PHP:

class MyClass { public $MyMemberArray; __construct() { $this->MyMemberArray = array(); } } 

I follow the examples in Advanced PHP Programming and Extending and Embedding PHP , and I can declare a class that has integer properties in PHP_MINIT_FUNCTION .

However, when I use the same approach to declare an array property in PHP_MINIT_FUNCTION , the following error message appears at runtime:

 PHP Fatal error: Internal zval can't be arrays, objects or resources in Unknown on line 0 

Here is an example on page 557 of Advanced PHP Programming on how to declare a constructor that creates an array property, but the example code does not compile (the second “object” seems redundant).

I fixed the error and applied it to my code:

 PHP_METHOD(MyClass, __construct) { zval *myarray; zval *pThis; pThis = getThis(); MAKE_STD_ZVAL(myarray); array_init(myarray); zend_declare_property(Z_OBJCE_P(pThis), "MyMemberArray", sizeof("MyMemberArray"), myarray, ZEND_ACC_PUBLIC TSRMLS_DC); } 

And this will compile, but the same runtime error when building.

+4
source share
1 answer

The answer is to use add_property_zval_ex() in the constructor, not zend_declare_property() .

The following works as intended:

 PHP_METHOD(MyClass, __construct) { zval *myarray; zval *pThis; pThis = getThis(); MAKE_STD_ZVAL(myarray); array_init(myarray); add_property_zval_ex(pThis, "MyMemberArray", sizeof("MyMemberArray"), myarray); } 
+6
source

All Articles