note 86374 added to language.oop5.references
| From: | IvanBertona at osu1 dot php dot net | Date: | Wed, 15 Oct 2008 15:45:08 +0000 |
| Subject: | note 86374 added to language.oop5.references | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-145383@lists.php.net to get a copy of this message | ||
A point that in my opinion is not stressed enough in the manual page is that in PHP5, passing an
object as an argument of a function call with no use of the & operator means passing BY VALUE an
unique identifier for that object (intended as instance of a class), which will be stored in another
variable that has function scope.
This behaviour is the same used in Java, where indeed there is no notion of passing arguments by
reference. On the other hand, in PHP you can pass a value by reference (in PHP we refer to
references as "aliases"), and this poses a threat if you are not aware of what you are
really doing. Please consider these two classes:
<?php
class A
{
function __toString() {
return "Class A";
}
}
class B
{
function __toString() {
return "Class B";
}
}
?>
In the first test case we make two objects out of the classes A and B, then swap the variables using
a temp one and the normal assignment operator (=).
<?php
$a = new A();
$b = new B();
$temp = $a;
$a = $b;
$b = $temp;
print('$a: ' . $a . "\n");
print('$b: ' . $b . "\n");
?>
As expected the script will output:
$a: Class B
$b: Class A
Now consider the following snippet. It is similar to the former but the assignment $a = &$b
makes $a an ALIAS of $b.
<?php
$a = new A();
$b = new B();
$temp = $a;
$a = &$b;
$b = $temp;
print('$a: ' . $a . "\n");
print('$b: ' . $b . "\n");
?>
This script will output:
$a: Class A
$b: Class A
That is, modifying $b reflects the same assignment on $a... The two variables end pointing to the
same object, and the other one is lost. To sum up is a good practice NOT using aliasing when
handling PHP5 objects, unless your are really really sure of what you are doing.
----
Server IP: 69.147.83.197
Probable Submitter: 128.238.35.14
----
Manual Page -- http://www.php.net/manual/en/language.oop5.references.php
Edit -- https://master.php.net/note/edit/86374
Del: integrated -- https://master.php.net/note/delete/86374/integrated
Del: useless -- https://master.php.net/note/delete/86374/useless
Del: bad code -- https://master.php.net/note/delete/86374/bad+code
Del: spam -- https://master.php.net/note/delete/86374/spam
Del: non-english -- https://master.php.net/note/delete/86374/non-english
Del: in docs -- https://master.php.net/note/delete/86374/in+docs
Del: other reasons-- https://master.php.net/note/delete/86374
Reject -- https://master.php.net/note/reject/86374
Search -- https://master.php.net/manage/user-notes.php