如何在php扩展中读取常量属性?

时间:2013-08-31 14:36:51

标签: php php-extension php-internals

我使用zend_declare_class_constant_stringl宏来声明一个常量属性,但我不知道如何读取常量? 声明代码:

zend_declare_class_constant_stringl(myclass_ce,ZEND_STRL("WEL"),ZEND_STRL("welcome\n") TSRMLS_CC);

我想使用zend_read_propertyzend_read_static_property来读取常量属性,但它不起作用!

(1): 我使用zend_read_static_property

ZEND_METHOD(myclass,getName){
zval *name;
char *str;
zend_class_entry *ce;
ce=Z_OBJCE_P(getThis());
name=zend_read_static_property(ce,ZEND_STRL("name"),0 TSRMLS_CC);
str=Z_STRVAL_P(name);
RETURN_STRINGL(str,Z_STRLEN_P(name),1);
}

[root @ localhost myext] #php -f /var/www/html/myclass.php

Notice: Undefined property: myclass::$WEL in /var/www/html/myclass.php on line 3
(null)PHP Fatal error:  Access to undeclared static property: myclass::$name in      /var/www/html/myclass.php on line 5

(2)我使用zend_read_property:

ZEND_METHOD(myclass,getName){
zval *name;
char *str;
zend_class_entry *ce;
ce=Z_OBJCE_P(getThis());
name=zend_read_property(ce,getThis(),ZEND_STRL("name"),0 TSRMLS_CC);
str=Z_STRVAL_P(name);
RETURN_STRINGL(str,Z_STRLEN_P(name),1);
}

[root @ localhost myext] #php -f /var/www/html/myclass.php

Notice: Undefined property: myclass::$WEL in /var/www/html/myclass.php on line 3
(null)silenceperPHP Fatal error:  Access to undeclared static property: myclass::$BYE in Unknown on line 0

1 个答案:

答案 0 :(得分:2)

使用zend_get_constant_ex

zval c;

if (zend_get_constant_ex(ZEND_STRL("ClassName::CONSTANT_NAME"), &c, NULL, 0 TSRMLS_CC) == SUCCESS) {
    // ...
}

NULL是执行提取的类范围(如果你想使用像self这样的东西)。 0是标志,例如ZEND_FETCH_CLASS_SILENT