4

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

class MyClass
{
    public $MyMemberArray;

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

I'm following the examples in "Advanced PHP Programming" and "Extending and Embedding PHP" and I'm able to 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, I get the following error message at runtime:

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

There's an example on page 557 of Advanced PHP Programming of how to declare a constructor which creates an array property, but the example code doesn't compile (the second "object" seems to be redundant).

I fixed the bug and adapted 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 compiles, but it gives the same runtime error on construction.

1 Answer 1

6

The answer is to use add_property_zval_ex() in the constructor, rather than 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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

but do you know WHY this is the answer? what is the reasoning?
The reasoning has to do with how a zval is created. It is a long winded explaination, trust me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.