Passing by reference in PHP

I have some general dissatisfaction with how link passing works in PHP based on the Java background. This may have been spoken about before, so I'm sorry if this may seem unnecessary.

I am going to give an example code so that everything is 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 use:

 <?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 out of programming in Java or C # in PHP would expect the code above:

 Michael Jerry 

However, it does not output:

 Michael Michael 

I know that this can be fixed using &. Understanding this, I understand that this is because the link is passed to the function by value (copy of the link). But for me this is an unexpected / inconsistent behavior, so the question will be: is there any specific reason or benefit for which they decided to do it this way?

+4
source share
2 answers

Your code will work as expected if it is used as follows:

 function changePerson(Person &$person) // <- & to state the reference { $person = new Person("Jerry"); } $person = new Person("John"); changeName($person); echo $person->getName() . PHP_EOL; changePerson($person); echo $person->getName() . PHP_EOL; 

See output: http://codepad.org/eSt4Xcpr

One of the key points of PHP 5 OOP, which is often mentioned, is that "objects are passed by default by default." This is not entirely true.

A PHP reference is an alias that allows two different variables to write the same value. Starting in PHP 5, the object variable no longer contains the object as a value. It contains only the object identifier, which allows object accessories to find the actual object. When an object is sent with an argument returned or assigned to another variable, the different variables are not aliases: they contain a copy of the identifier that points to the same object.

Quote from http://php.net/manual/en/language.oop5.references.php .

+1
source

The object itself is actually passed by reference, otherwise your first echo does not output Michael .

What happens in the second example is that you destroy the (local) link to the source object and refer to your variable name to the new object with the local scope in the function.

This makes sense to me, since you can destroy / replace your object with something completely different by simply assigning a new value to the variable in the function.

+2
source

All Articles