我对编写扩展程序还不陌生。我正在努力使它成为结果:

class FooClass {
    private $elements = array();
}


实例化FooClass时出现错误:

PHP致命错误:无法访问私有属性ArrayClass :: $ elements

我确切地知道为什么会这样,只是我不知道将类定义创建为数组的正确方法。到目前为止,这是我所知道的,这很简单:

static zend_class_entry *foo_class_ptr;

void create_class_properties(TSRMLS_D) {
     zend_declare_property_null(foo_class_ptr, "elements", strlen("elements"), ZEND_ACC_PRIVATE);
}

ZEND_METHOD(foo_class, __construct) {
    zval *this = getThis();
    zval *elements;

    MAKE_STD_ZVAL(elements);
    array_init(elements);

    add_property_zval_ex(this, "elements", sizeof("elements"), elements);
}

static zend_function_entry foo_class_methods_def[] = {
    PHP_ME(foo_class, __construct, NULL, ZEND_ACC_PUBLIC)
    {NULL, NULL, NULL}
};

void create_class_def(TSRMLS_D) {
    zend_class_entry ce;
    INIT_CLASS_ENTRY(ce, "FooClass", foo_class_methods_def);

    foo_class_ptr = zend_register_internal_class(&ce);
}


从PHP_MINIT_FUNCTION()调用create_class_def get。这里有一个类似的问题:How do I add an array as an Object Property to a class declared within a PHP extension?,但它没有解决私有/受保护的访问。

谢谢

最佳答案

最简单的方法可能是使用zend_update_property

void zend_update_property(zend_class_entry *scope, zval *object, const char *name, int name_length, zval *value TSRMLS_DC);

name_length不包含终止符。

关于c - 如何在php ext中的类中将私有(private)属性创建为数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10052739/

10-11 23:06
查看更多