如何添加一个数组作为对象属性的PHP扩展中声明的类? [英] How do I add an array as an Object Property to a class declared within a PHP extension?

查看:230
本文介绍了如何添加一个数组作为对象属性的PHP扩展中声明的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的PHP扩展申报相当于下面的PHP类:

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

class MyClass
{
    public $MyMemberArray;

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

我按照高级PHP编程和<一个例子HREF =htt​​p://rads.stackoverflow.com/amzn/click/067232704X相对=nofollow>扩展和嵌入PHP ,我可以宣布,在<$有整数性质的一类C $ C> PHP_MINIT_FUNCTION 。

然而,当我用同样的方式来声明在 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

有一个问题就是怎样声明它创建一个数组属性的构造高级PHP编程557页上的例子,但例如code不编译(第二个对象,似乎是多余的)。

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).

我固定的bug,它适应了我的code:

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.

推荐答案

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

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

这篇关于如何添加一个数组作为对象属性的PHP扩展中声明的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆