如何将数组作为对象属性添加到 PHP 扩展中声明的类中?

发布于 2024-07-26 18:41:29 字数 1223 浏览 6 评论 0原文

我希望我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小伙你站住 2024-08-02 18:41:30

答案是在构造函数中使用add_property_zval_ex(),而不是zend_declare_property()

以下工作按预期进行:

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);
}

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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文