如何将数组作为对象属性添加到 PHP 扩展中声明的类中?
我希望我的 PHP 扩展声明一个与以下 PHP 等效的类:
class MyClass
{
public $MyMemberArray;
__construct()
{
$this->MyMemberArray = array();
}
}
我正在遵循“高级 PHP 编程" 和 "扩展和嵌入 PHP" 并且我能够声明一个类在 PHP_MINIT_FUNCTION
中具有整数属性。
但是,当我使用相同的方法在 PHP_MINIT_FUNCTION
中声明数组属性时,我在运行时收到以下错误消息:
PHP Fatal error: Internal zval's can't be arrays, objects or resources in Unknown on line 0
高级 PHP 编程第 557 页上有一个示例,说明如何声明一个构造函数,该构造函数创建一个数组属性,但示例代码无法编译(第二个“对象”似乎是多余的)。
我修复了该错误并将其改编为我的代码:
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);
}
并且可以编译,但它在构造时给出相同的运行时错误。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
答案是在构造函数中使用
add_property_zval_ex()
,而不是zend_declare_property()
。以下工作按预期进行:
The answer is to use
add_property_zval_ex()
in the constructor, rather thanzend_declare_property()
.The following works as intended: