PHP (BASIC) Assignment of Object and Class

0

I have a question ...

The following code:

<?php

$instancia = new ClaseSencilla();

$asignada   =  $instancia;
$referencia =& $instancia;

$instancia->var = '$asignada tendrá este valor';

$instancia = null; // $instancia y $referencia son null

var_dump($instancia);
var_dump($referencia);
var_dump($asignada);
?>

Which produces the following output:

NULL
NULL
object(ClaseSencilla)#1 (1) {
   ["var"]=>
     string(27) "$asignada tendrá este valor"
}
  

Line number 5: "string (27)" $ assigned ......... "

Why do you return that? I ask because my logic (which is certainly wrong) says that I should return NULL or an error because at the time I was assigned the value of $instancia" a "$asignada ... $asignada had no value in $var , the value was assigned after! ( $instancia->var = $asignada will have ....)

The example I did not try it out of the official documentation of php: link

I hope you understand my query and that you can get rid of my doubts!

Thank you!

    
asked by krowa 08.02.2017 в 21:24
source

1 answer

1

We have to:

  

When an existing instance of a class is assigned to a new variable, the latter will access the same instance as the object assigned to it.

  

References in PHP are means of accessing the same content of a variable by different names. They are not like the pointers of C; for example, you can not perform pointer arithmetic with them, they are not really memory addresses, etc. See What are NOT the References? for more information. Note that in PHP the name of the variable and the content of the variable are different things, so the same content can have different names.

What he means is that:

$asignada = $instancia; //Crea una nueva var que apunta a la instancia.
$referencia =& $instancia; //Crea una var que apunta por referencia al valor de la var $instancia.

When doing:

$instancia = null;

What we are saying is that the new value of $instancia is null , as simple as that. The variable $asignada keeps pointing to the instance.

    
answered by 08.02.2017 в 22:11