Home » Php » Passing a variable by reference into a PHP extension

Passing a variable by reference into a PHP extension

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’m writing a PHP extension that takes a reference to a value and alters it. Example PHP:

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

What’s the right approach?

How to&Answers:

Edit 2011-09-13:
The correct way to do this is to use the ZEND_BEGIN_ARG_INFO() family of macros – see Extending and Embedding PHP chapter 6 (Sara Golemon, Developer’s Library).

This example function takes one string argument by value (due to the ZEND_ARG_PASS_INFO(0) call) and all others after that by reference (due to the second argument to ZEND_BEGIN_ARG_INFO being 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);
}

Before adding the convert_to_null it would leak memory on every call (I’ve not whether this is necessary after adding ZENG_ARG_INFO() calls).