PHP扩展:用__ToString()将对象转换为字符串
题
在C中编写php扩展程序,我想转换一个用户land对象(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;
...
}
解决方案
反射模块可以做类似的事情
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中实现。您可能想检查它是否真的做您想要的
不隶属于 StackOverflow