Geek Stuff: Bizarre PHP Code

I won't incriminate this project's coders, but they do sell their work that is based on vBulletin. One of their free projects contains a function that has three arguments passed to it. The first argument is immediately overwritten by a global. Here is a stripped down example:

 <?php
$hello = 'hello';
$world = 'world';

function test(&$hello) {
    global $hello;

    echo "$hello\n";
}

test($world);
echo "$hello $world\n";
?>

And the output of my function:

$ php test.php
hello
hello world

$world is passed by reference as $hello. It is promptly ignored in favor of the global $hello variable, without even overwriting $world. They should remove the required parameter $hello.

garrettw's picture

Weird.

And they even bothered to put an '&' in front of it. lol. I don't get it either.

Chris's picture

Probably a Typo

A couple other things make this doubly weird. This is the main function call for the project. The variable that they pass is the equivalent of my calling test($hello). I only used test($world) in the example above to demonstrate what is happening to the variable.

A programmer was probably debugging and got distracted (I hope Tongue). The PHP behavior wasn't exactly what I expected since the variable was passed by reference. Instead two copies of the variable were made available, with the global one taking precedence.

Klaus's picture

This looks like php4 code,

This looks like php4 code, imho. Of course, it's simplified. But explicitly passing by reference is no longer necessary in most cases in php >= 5.0.