Bu global değişkene atarken $this önünde & kaldırırsanız, o inşaat yoldur, ama neden emin değilim, bu iş olacak.
To illustrate that, the following portion 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;
Aşağıdaki çıktıyı verir:
10
Here are the differences with your code :
- Ben kaldırmak
& önce $this: PHP 5 ile, nesnelerle çalışma olduğu için hiç gerek yoktur
- I translated the code to real PHP 5 :
As a sidenote, the code you posted should have given you the following warning :
Strict standards: Creating default object from empty value
Notlar:
- PHP 5.3.2 kullanıyorum
E_ALL içermez E_STRICT (source) em>
EDIT after some more searching :
Geçmekte References Explained section of the PHP manual, and, more specifically the What References Do page, there is a warning given that says (quoting),
If you assign a reference to a
variable declared global inside a
function, the reference will be
visible only inside the function.
You
can avoid this by using the $GLOBALS
array.
And there is an example going with it.
Trying to use $GLOBALS in your code, I have this portion of code :
$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;
Ve ben şu çıktıyı alıyorum:
10
Hangi iş gibi görünüyor ;-)
If I replace the __construct method by this :
public function __construct()
{
global $global_obj;
$global_obj = & $this;
}
Bu işe yaramazsa ...
So it seems you should not use global, here, but $GLOBALS.
Kılavuzda verilen açıklama:
Think about global $var; as a
shortcut to $var =&
$GLOBALS['var'];.
Thus assigning
another reference to $var only
changes the local variable's
reference.
And, just so it's said : using global variables is generally not quite a good idea -- and, in this specific situation, it feels like a very bad idea...
(Now, if this question what just to understand why... Well, I can understand your curiosity ;-) )