Pergunta

Eu estou escrevendo uma extensão do PHP que leva uma referência a um valor eo altera. Exemplo PHP:

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

O que é a abordagem correta?

Foi útil?

Solução

Editar 2011-09-13 : A maneira correta de fazer isso é usar a família ZEND_BEGIN_ARG_INFO() de macros - veja Estendendo and Embedding PHP Capítulo 6 (Sara Golemon, Biblioteca do desenvolvedor) .

Esta função exemplo leva argumento uma cadeia de valor (devido à chamada ZEND_ARG_PASS_INFO(0)) e todos os outros depois que por referência (devido ao segundo argumento para ZEND_BEGIN_ARG_INFO sendo 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);
}

Antes de adicionar o convert_to_null seria vazar memória em cada chamada (eu não tenho se isso for necessário após a adição de chamadas ZENG_ARG_INFO()).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top