Answer the question
In order to leave comments, you need to log in
(PHP5) Why does assignment work like cloning?
Code from this page php.net/manual/ru/language.oop5.basic.php from example #4
<?php
$instance = new SimpleClass();
$assigned = $instance;
$reference =& $instance;
$instance->var = '$assigned будет иметь это значение';
$instance = null; // $instance и $reference становятся null
var_dump($instance);
var_dump($reference);
var_dump($assigned);
?>
NULL
NULL
object(SimpleClass)#1 (1) {
["var"]=>
string(30) "$assigned будет иметь это значение"
}
Answer the question
In order to leave comments, you need to log in
There is no cloning magic here.
First, let's figure out what $instance stores. It stores the REFERENCE to the object and not the object itself. With a simple assignment by value, the value of the variable is copied, and we have it just a reference to an object. As a result, we already have two references to one object.
When assigning a value to the $reference variable by reference, we have two variables that share the same value. A value is a reference to an object.
When we overwrite the reference in $instance, that is, we change the value of it, it also changes in $reference, since they divide one value into two. $assigned has its own object reference.
$instance = new SimpleClass(); // количество ссылок на экземпляр SimpleClass - 1
$assigned = $instance; // количество ссылок на экземпляр SimpleClass - 2
$reference =& $instance; // количество ссылок на экземпляр SimpleClass - 2
$instance = null; // количество ссылок на экземпляр SimpleClass - 1
Read the php.net/manual/en/language.operators.assignment.php
documentation for
the difference
Assignment Operators
...
Note that the assignment copies the original variable to the new one (assignment by value), so changes to one will not affect the other. This may also have relevance if you need to copy something like a large array inside a tight loop.
...
Assignment by Reference
...
Assignment by reference means that both variables end up pointing at the same data, and nothing is copied anywhere.
...
in my opinion everything is very clear. in the first case, a copy is created, in the second, a reference is taken and the variable refers to the same object.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question