note 78789 added to language.references
| From: | henrik at newdawn dot dk | Date: | Sat, 27 Oct 2007 22:21:49 +0000 |
| Subject: | note 78789 added to language.references | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-131782@lists.php.net to get a copy of this message | ||
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
)
----
Server IP: 217.160.72.57
Probable Submitter: 212.242.182.191
----
Manual Page -- http://www.php.net/manual/en/language.references.php
Edit -- https://master.php.net/note/edit/78789
Del: integrated -- https://master.php.net/note/delete/78789/integrated
Del: useless -- https://master.php.net/note/delete/78789/useless
Del: bad code -- https://master.php.net/note/delete/78789/bad+code
Del: spam -- https://master.php.net/note/delete/78789/spam
Del: non-english -- https://master.php.net/note/delete/78789/non-english
Del: in docs -- https://master.php.net/note/delete/78789/in+docs
Del: other reasons-- https://master.php.net/note/delete/78789
Reject -- https://master.php.net/note/reject/78789
Search -- https://master.php.net/manage/user-notes.php