PHP扩展:使用__toString()将对象转换为字符串

时间:2010-01-15 11:41:07

标签: php c tostring php-5.3

在C中编写PHP扩展,我想将userland对象(IS_OBJECT)转换为通过__toString()的字符串(如果有),否则失败。我该怎么用? 输出中我不需要另外zval,只需char *

zval *zo;

switch (Z_TYPE_P(zo)) {
case IS_STRING:
    ... Z_STRVAL_P(zo) ...
    break;
case IS_OBJECT:
    ... ???(zo) ...
    break;
...
}

1 个答案:

答案 0 :(得分:1)

反射模块的功能类似于

ZVAL_STRINGL(&fname, "__tostring", sizeof("__tostring") - 1, 1);
result= call_user_function_ex(NULL, &object, &fname, &retval_ptr, 0, NULL, 0, NULL TSRMLS_CC);
zval_dtor(&fname);

if (result == FAILURE) {
    _DO_THROW("Invocation of method __toString() failed");
    /* Returns from this function */
}

然后你用Z_STRVAL_P()提取char * 但我你也可以使用

case IS_OBJECT:
  if ( SUCCESS==zend_std_cast_object_tostring(uservar, uservar, IS_STRING TSRMLS_CC) ) {
    int len = Z_STRLEN_P(uservar);
    char* pValue = Z_STRVAL_P(uservar);
    ...
  }

zend_std_cast_object_tostring()在zend / zend_object_handlers.c中实现。您可能想要检查它是否真的符合您的要求