I want my PHP extension to declare a class equivalent to the following PHP:
我希望我的PHP扩展声明一个等效于以下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
.
我正在按照“高级PHP编程”和“扩展和嵌入PHP”中的示例进行操作,并且我能够在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_MINIT_FUNCTION中声明一个数组属性时,我在运行时收到以下错误消息:
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).
高级PHP编程的第557页有一个例子,说明如何声明一个创建数组属性的构造函数,但是示例代码没有编译(第二个“对象”似乎是多余的)。
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 个解决方案
#1
The answer is to use add_property_zval_ex()
in the constructor, rather than zend_declare_property()
.
答案是在构造函数中使用add_property_zval_ex(),而不是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);
}
#1
The answer is to use add_property_zval_ex()
in the constructor, rather than zend_declare_property()
.
答案是在构造函数中使用add_property_zval_ex(),而不是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);
}