Estensione PHP:converti un oggetto in stringa con __toString()
Domanda
Scrivendo un'estensione PHP in C, voglio convertire un oggetto userland (IS_OBJECT
) a una stringa passante __toString()
se ne ha uno, e fallire altrimenti.Cosa dovrei usare?Non ne ho bisogno di un altro zval
in uscita, solo a char *
.
zval *zo;
switch (Z_TYPE_P(zo)) {
case IS_STRING:
... Z_STRVAL_P(zo) ...
break;
case IS_OBJECT:
... ???(zo) ...
break;
...
}
Soluzione
Il modulo di riflessione fa qualcosa del genere
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 */
}
E poi estrarresti il char* con Z_STRVAL_P().
Ma io Indovinare potresti anche usare
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() è implementato in zend/zend_object_handlers.c.Potresti voler verificare se fa davvero quello che vuoi
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow