Wednesday, January 14. 2004
I don't know about PHP 4.3.x (I haven't tested).. but in PHP 5 the following script is completely valid:
<?php
class weird {
var $myvar;
function __construct() {
$myvar = "Z";
$this->myvar = "A";
$this->$myvar = "B";
$this->${'myvar'} = "C";
$this->${'$myvar'} = "D";
echo 'this->myvar: '.$this->myvar."\n";
echo 'this->$myvar: '.$this->$myvar."\n";
echo 'this->${\'myvar\'}: '.$this->${'myvar'}."\n";
echo 'this->${\'$myvar\'}: '.$this->${'$myvar'}."\n";
echo 'this->$$$$$$$myvar: '.$this->$$$$$$$myvar."\n";
echo 'this->$$$$$$${\'$$$myvar\'}: '.$this->$$$$$$${'$$$myvar'}."\n";
}
}
new weird();
?>
Not only is it valid, but the output is also interesting:
this->myvar: A
this->$myvar: C
this->${'myvar'}: C
this->${'$myvar'}: D
this->$$$$$$$myvar: D
this->$$$$$$${'$$$myvar'}: D
If you remove the declaration of the local $myvar in the constructor you get:
this->myvar: A
this->$myvar: D
this->${'myvar'}: D
this->${'$myvar'}: D
this->$$$$$$$myvar: D
this->$$$$$$${'$$$myvar'}: D
I don't *think* this is a bug, from what I understand of the way the engine works. However, it is quite odd isn't it? Here's something that's even more interesting -- did you know you *can* define a variable that starts with a
number?
<?php
${1} = "Hi";
echo "${1}\n";
?>
In fact, you can put just about any expression you want in between the ${ } and create a variable (including NULL). Of course, it is strongly recommended you EVER do such things in a real PHP script -- I just thought I'd share.