Another explanation

The code

$global_obj = null;
class my_class
{
       var $value;
       function my_class()
       {
               global $global_obj;
               $global_obj = &$this;
       }
}
$a = new my_class;
$a->my_value = 5;
$global_obj->my_value = 10;
echo $a->my_value;

echo 5, not 10.

"At first glance, it seems that the constructor my_class maintains a reference to itself inside the $ global_obj variable. Therefore, we would expect that when we later change the value of $ global_obj-> my_value to 10, the corresponding value in $ a will also change. Unfortunately, the new operator does not return the link, but a copy of the newly created object.

I still do not understand this, so can someone explain it differently and help me understand?

+3
source share
1 answer

Not sure why this works like that, but if you delete &before $thisby assigning it to a global variable, it will work.


To illustrate this, the following piece of code:

$global_obj = null;
class my_class
{
   public $my_value;
   public function __construct()
   {
        global $global_obj;
        $global_obj = $this;
   }
}
$a = new my_class;
$a->my_value = 5;

$global_obj->my_value = 10;
echo $a->my_value;

:

10


:

  • & $this: PHP 5,
  • PHP 5:
    • __construct
    • public/protected/private, var properties


, , :

Strict standards: Creating default object from empty value

:

  • PHP 5.3.2
  • E_ALL E_STRICT ()



:

Explained PHP , , , , ():

, , .
, $GLOBALS.

.


$GLOBALS , :

$global_obj = null;
class my_class
{
   public $my_value;
   public function __construct()
   {
        $GLOBALS['global_obj'] = & $this;
   }
}
$a = new my_class;
$a->my_value = 5;

$global_obj->my_value = 10;
echo $a->my_value;

:

10

, ; -)


__construct :

public function __construct()
{
    global $global_obj;
    $global_obj = & $this;
}

...


, , global , $GLOBALS.

, :

global $var; $var =& $GLOBALS['var'];. , $var .



: , , - ...

(, , , ... , ;-))

+5

Source: https://habr.com/ru/post/1742617/


All Articles