Paolo
Paolo

Reputation: 15847

PHP: Is valid to call a function passing by reference a variable not yet defined?

As the title asks: is ok to call a function passing by reference a variable not yet defined ?

Let's assume the variable will be set inside the function in any case.

I post example code to give context to the question:

function doStuff( &$error )
{
    $error = false;

    // Start doing stuff...
    // ...

    if( /* SOMETHING WRONG */ )
    {
        $error = "Something went wrong";
    }

}


doStuff( $err ); // $err is not defined!


if( $err !== false )
{
    // Handle the error, ex.

    echo $err;
    exit;
}

I tried on the cli with error_reporting ( E_ALL ); and no errors were reported.

Still I ask confirmation if it's safe, has no drawbacks, is not bad coding pattern...

Upvotes: 3

Views: 95

Answers (2)

deceze
deceze

Reputation: 522500

Variables which are passed as referenced parameters do not have to be initialised beforehand; what you're doing is fine. A classic example of such a use case is preg_match:

int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )

The &$matches parameter is used sort of as a secondary optional output channel in addition to the normal return value (an int). Since that is one of the primary uses of pass-by-reference values, the language designers have taken care that it can be used in the simplest way possible:

if (preg_match($foo, $bar, $match)) {
    echo $match[0];
}

Passing the variable as argument for the referenced parameter initialises the variable in the caller's scope. If you had to use it this way every time, this would lead to pretty annoying code:

$match = null;
if (preg_match($foo, $bar, $match)) {
    echo $match[0];
}

Upvotes: 2

Aganju
Aganju

Reputation: 6405

I would consider that fine, and do it myself often - in right the design you showed. It depend how 'purist' you want to be; there are probably people who say you shouldn't do that. Either way it is important to clear or preset the variable right at the beginning of the function.

The only drawback is that potentially a larger code base is maintained by multiple people or groups, and the person working on the caller might not be in contact with the person working on the function. This can lead to issues if the design is not known to one of them, as he could assume the variable is already initialized - and this is why a more puristic approach would say to not do it.

Upvotes: -1

Related Questions