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?
user1703809
source share