note 88570 deleted from language.variables.scope by crell
| From: | crell@php.net | Date: | Thu, 31 Mar 2022 19:33:44 +0000 |
| Subject: | note 88570 deleted from language.variables.scope by crell | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-217917@lists.php.net to get a copy of this message | ||
Note Submitter: nullhility at gmail dot com
----
Like functions, if you declare a variable in a class, then set it as global in that class, its value
will not be retained outside of that class either.
<?php
class global_reference
{
public $val;
public function __construct () {
global $var;
$this->val = $var;
}
public function dump_it ()
{
debug_zval_dump($this->val);
}
public function type_cast ()
{
$this->val = (int) $this->val;
}
}
$var = "x";
$obj = new global_reference();
$obj->dump_it();
$obj->type_cast();
echo "after change ";
$obj->dump_it();
echo "original $var\n";
?>
The work-around is of course changing the assignment in the constructor to a reference assignment as
such:
<?php
//....
$this->val = &var;
//....
?>
If the global you're setting is an object then no reference is necessary because of the way PHP
deals with objects. If you don't want to reference to the same object however you can use the
clone keyword.
<?php
//...
global $Obj;
$this->obj_copy = clone $Obj;
//...
?>
[EDIT BY danbrown AT php DOT net: Merged all thoughts and notes by this author into a single note.]