【问题标题】:how to read a constant property in php extension?如何读取 php 扩展中的常量属性?
【发布时间】:2013-09-04 03:36:52
【问题描述】:

我使用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

【问题讨论】:

  • “它行不通!” 这样的说法有点不具体,不清楚您实际上期望什么以及发生了什么。愿意分享更多信息吗?

标签: php php-extension php-internals


【解决方案1】:

使用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.

【讨论】:

  • 像这样:ZEND_METHOD(myclass,__construct){ zval wel; zend_class_entry *ce; ce=Z_OBJCE_P(getThis()); zend_get_constant_ex(ZEND_STRL("self::WEL"),&wel,ce,0 TSRMLS_CC); php_printf("%s",Z_STRVAL(wel)); } 共检测到 1 次内存泄漏
  • @silenceper 当然之后你必须zval_dtor zval
  • 缺少的是ClassName::,这个答案非常有用,尽管我想问一下,是否有关于使用 c 进行 PHP 扩展的好资源?
猜你喜欢
  • 1970-01-01
  • 2017-02-17
  • 2022-01-05
  • 2021-03-11
  • 1970-01-01
  • 2018-07-08
  • 1970-01-01
  • 2010-11-14
  • 1970-01-01
相关资源
最近更新 更多