PHP 7.2.0 Beta 1 Released

Voting

Please answer this simple SPAM challenge: max(four, two)?
(Example: nine)

The Note You're Voting On

henrik at newdawn dot dk
9 years ago
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
)

<< Back to user notes page

To Top