0

我仍然是编写扩展程序的新手。我试图让这成为结果:

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。这里有一个类似的问题:如何将数组作为对象属性添加到 PHP 扩展中声明的类?但它没有解决私有/受保护的访问。

谢谢

4

1 回答 1

0

最简单的方法可能是使用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不包括终结者。

于 2012-04-07T18:17:38.557 回答