note 78789 deleted from language.references by cmb
| From: | cmb@php.net | Date: | Sun, 01 Sep 2019 07:46:10 +0000 |
| Subject: | note 78789 deleted from language.references by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-212064@lists.php.net to get a copy of this message | ||
Note Submitter: henrik at newdawn dot dk
----
A note for those of you that are using constructs like the following:
return $this->$MyVarName
in your objects.
Consider the following:
class Test {
var $MyArray = array();
function add($var) {
$this->$var[rand(1,100)] = rand(1,100);
}
function show($var) {
echo "\nEcho from Test:\n";
print_r($this->$var);
}
}
$test = new Test();
$test->show('MyArray');
$test->add('MyArray');
$test->add('MyArray');
$test->add('MyArray');
$test->show('MyArray');
will output
Echo from Test:
Array
(
)
Fatal error: Cannot access empty property in /home/webroot/framework_devhost_dk/compiler/test2.php
on line 5
For this to work properly you have to use a construct similar to this:
class Test {
var $MyArray = array();
function add($var) {
$tmp =& $this->$var; //This is the trick... strange but true ;)
$tmp[rand(1,100)] = rand(1,100);
}
function show($var) {
echo "\nEcho from Test:\n";
print_r($this->$var);
}
}
$test = new Test();
$test->show('MyArray');
$test->add('MyArray');
$test->add('MyArray');
$test->add('MyArray');
$test->show('MyArray');
Will output:
Echo from Test:
Array
(
)
Echo from Test:
Array
(
[19] => 17
[53] => 57
[96] => 43
)