I have a bit of a general dissatisfaction about the way passing by reference works in PHP, coming from a Java background myself. This might have been talked about before on SO, so I’m sorry if this might seem redundant.
I’m going to give a code example to make things clear. Say we have a Person class:
<?php
class Person
{
private $name;
public function __construct($name)
{
$this->name = $name;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
?>
and the following usage:
<?php
require_once __DIR__ . '/Person.php';
function changeName(Person $person)
{
$person->setName("Michael");
}
function changePerson(Person $person)
{
$person = new Person("Jerry");
}
$person = new Person("John");
changeName($person);
echo $person->getName() . PHP_EOL;
changePerson($person);
echo $person->getName() . PHP_EOL;
?>
Now I, and many others coming from programming in Java or C# into PHP, would expect the above code to output:
Michael
Jerry
However, it does not, it outputs:
Michael
Michael
I know it can be fixed by using &. From looking into it, I understand that this is because the reference is passed into the function by value (a copy of the reference). But this to me constitutes an unexpected / inconsistent behavior, so the question would be: Is there any particular reason or benefit for which they chose to do it this way?
Your code would work as expected if used this way:
See the output: http://codepad.org/eSt4Xcpr
Quoted from http://php.net/manual/en/language.oop5.references.php.