My Photos

www.flickr.com
This is a Flickr badge showing public photos and videos from coogle. Make your own badge here.

Quicksearch

Talk about strange PHP

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.
Bookmark Talk about strange PHP  at del.icio.us Digg Talk about strange PHP Bloglines Talk about strange PHP Technorati Talk about strange PHP Fark this: Talk about strange PHP Bookmark Talk about strange PHP  at YahooMyWeb Bookmark Talk about strange PHP  at Furl.net Bookmark Talk about strange PHP  at reddit.com Bookmark Talk about strange PHP  at blinklist.com Bookmark Talk about strange PHP  at Spurl.net Bookmark Talk about strange PHP  at NewsVine Bookmark Talk about strange PHP  at Simpy.com Bookmark Talk about strange PHP  at blogmarks Bookmark Talk about strange PHP  with wists Bookmark Talk about strange PHP  at Ma.gnolia.com wong it! Bookmark using any bookmark manager!

Trackbacks

No Trackbacks

Comments
Display comments as (Linear | Threaded)

No comments

The author does not allow comments to this entry