|
What’s bad practice is the following:
function display($message) {
echo $message;
}
$myMessage = 'Hello World!';
// Call time pass by reference - bad practice!
display(&$message);
That’s known as a call-time pass-by-reference, which PHP controls with the following setting in php.ini:
allow_call_time_pass_reference = Off
By default, in recent PHP releases the above setting should be switched to Off; turning it on is “frowned upon” by PHP’s makers. Switched off, PHP will generate warning errors every time a function call specifies an argument should be passed by reference. As such, it’s good practice to leave this setting off.
The reason why call time pass by reference is a “bad thing” is that call time passing by reference can make code extremely difficult to follow. I’ve occasionally seen PHP XML parsers written using a call-time pass-by-reference—it’s nearly impossible to gain any idea of what’s going on.
The “decision” as to whether a variable is passed by reference or not is one that belongs to the function being called, not the code that calls it. The above code written correctly would look like this:
// Accept by reference - good practice
function display(&$message)
{
echo $message;
}
$myMessage = 'Hello World!';
display($message);
|