Domanda

Sto scrivendo un'estensione di PHP che prende un riferimento a un valore e altera. Esempio PHP:

$someVal = "input value";
TestPassRef($someVal);
// value now changed

Qual è l'approccio giusto?

È stato utile?

Soluzione

Modifica 2011-09-13 : Il modo corretto per farlo è quello di utilizzare la ZEND_BEGIN_ARG_INFO() famiglia di macro - vedi estensione e Incorporare capitolo PHP 6 (Sara Golemon, Biblioteca del Developer) .

Questa funzione esempio prende un argomento stringa per valore (dovuta alla chiamata ZEND_ARG_PASS_INFO(0)) e tutti gli altri dopo che con riferimento (a causa del secondo argomento ZEND_BEGIN_ARG_INFO essere 1).

const int pass_rest_by_reference = 1;
const int pass_arg_by_reference = 0;

ZEND_BEGIN_ARG_INFO(AllButFirstArgByReference, pass_rest_by_reference)
   ZEND_ARG_PASS_INFO(pass_arg_by_reference)
ZEND_END_ARG_INFO()

zend_function_entry my_functions[] = {
    PHP_FE(TestPassRef, AllButFirstArgByReference)
};

PHP_FUNCTION(TestPassRef)
{
    char *someString = NULL;
    int lengthString = 0;
    zval *pZVal = NULL;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz", &someString, &lengthString, &pZVal) == FAILURE)
    {
        return;
    }

    convert_to_null(pZVal);  // Destroys the value that was passed in

    ZVAL_STRING(pZVal, "some string that will replace the input", 1);
}

Prima di aggiungere memoria convert_to_null sarebbe perdere su ogni chiamata (non se questo è necessaria dopo l'aggiunta di ZENG_ARG_INFO() chiamate ho).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top