I’ve found the following example on PHP Classes and Objects: The Basics, but I can’t understand what’s going on in the background.
There is a statement:
When assigning an already created instance of a class to a new variable, the new variable will access the same instance as the object that was assigned. This behavior is the same when passing instances to a function. A copy of an already created object can be made by cloning it.
I assume this is states that object are passed by reference by default, so one should clone it, if a real copy is intended to be made. (There is neither shallow-copy in PHP. Yes, there is a clone by default.)
Consider the following example (copied from the above link):
<?php
$instance = new SimpleClass();
$assigned = $instance;
$reference =& $instance;
$instance->var = '$assigned will have this value';
$instance = null; // $instance and $reference become null
var_dump($instance);
var_dump($reference);
var_dump($assigned);
?>
As has been told there, this outputs the following:
NULL
NULL
object(SimpleClass)#1 (1) {
["var"] => string(30) "$assigned will have this value"
}
I don’t understand.
If $assigned = $instance; is an assignment by reference (alias) on objects by default, than why $assigned still is an object of SimpleClass that holds the $var property with that string, while the NULL was assigned to $instance.
It’s misleading to say that
$assigned = $instanceis an assignment by reference. You can better think of it as if$instancewere a pointer: it has value (not reference) semantics, although many copies of it can point to the same object.On the other hand,
$reference =& $instancedoes create an alias: whatever happens to one of the variables is also immediately visible when the other is examined.