D
D
dontagr2014-08-05 09:09:16
PHP
dontagr, 2014-08-05 09:09:16

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 будет иметь это значение"
# }

I want to understand why actually $assigned did not become null?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pavel Solovyov, 2014-08-05
@dontagr

php.net/manual/en/language.oop5.references.php

I
Ilya Lesnykh, 2014-08-05
@Aliance

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 question

Ask a Question

731 491 924 answers to any question