【问题标题】:How to implement the parent :: __ construct () call in the php extension ?php扩展中如何实现parent::__construct()调用?
【发布时间】:2017-05-18 04:21:44
【问题描述】:

我想在php扩展中实现如下代码

class A{
    public function __construct(){
    }
}

class B extends A{
    public function __construct(){
        parent::__construct();
    }
}

我写了这些:

 zend_class_entry *a_class_ce, *b_class_ce;

    ZEND_METHOD(a_class, __construct){
    }

    ZEND_METHOD(b_class, __construct){
    }

    static zend_function_entry a_class_method[]={
            ZEND_ME(a_class, __construct, NULL, ZEND_ACC_PUBLIC)
            {NULL, NULL, NULL}
    };

    static zend_function_entry b_class_method[]={
            ZEND_ME(b_class, __construct, NULL, ZEND_ACC_PUBLIC)
            {NULL, NULL, NULL}
    };

    ZEND_MINIT_FUNCTION(test){
        zend_class_entry a_ce, b_ce;

        INIT_CLASS_ENTRY(a_ce, "A", a_class_method);
        a_class_ce = zend_register_internal_class(&a_ce TSRMLS_CC);

        INIT_CLASS_ENTRY(b_ce, "B", b_class_method);
        b_class_ce = zend_register_internal_class_ex(&b_ce, b_class_ce TSRMLS_CC);

        return SUCCESS;
    }

但是不知道怎么实现 parent::__construct();

如何实现parent :: __construct()?

【问题讨论】:

  • @Luke 我不是 PHP 大师,但嗯...不,IMO 这与 与 Zend 框架没有任何关系
  • @AnttiHaapala 谢谢,我离题了。

标签: php php-extension


【解决方案1】:

我没有机会对此进行准确测试,但根据我在 php-src 的一些核心扩展中看到的用法,它似乎可以工作:

void call_parent_constructor(zval* zobj)
{
    zend_class_entry* ce = zend_get_class_entry(zobj);
    zend_class_entry* parentEntry = ce->parent;

    if (parentEntry == NULL) {
        php_error(E_ERROR,"fail call_parent_constructor(): class has no parent");
        return;
    }

    zend_call_method(
        &zobj,
        parentEntry,
        &parentEntry->constructor,
        "__construct",
        sizeof("__construct")-1,
        NULL,
        0,
        NULL,
        NULL);
}

此示例假定您不需要向父构造函数传递任何参数。如果您需要传递参数,请注意 zend_call_method() 限制您仅传递 0、1 或 2 个参数。

更新我已经在 PHP 5 中测试了这种方法,它可以按预期工作。

【讨论】:

    猜你喜欢
    • 2011-03-29
    • 2010-12-08
    • 2017-01-14
    • 2014-08-06
    • 2017-03-07
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多