Answer the question
In order to leave comments, you need to log in
How does object variable assignment work in php?
Please help me to understand the code:
<?php
class SimpleClass {
public $var;
}
$instance = new SimpleClass();
$assigned = $instance;
$reference =& $instance;
$instance->var = '$assigned будет иметь это значение';
$instance = 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
Read about zval and call-by-reference in PHP ( reference counting basics ).
After assigning a new value to a property of the original object, the $assigned variable is set to a copy of the object stored in $instance prior to the assignment (passing by value). From here these variables refer to 2 different instances of the class. And the $reference variable is only a reference to $instance (passing by reference), so if the original is overwritten, the link will also be overwritten.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question