Categories
Fun PHP

did you know "you can have cheese burger" could be a variable name?

Well, I didn’t know. But I figured it out while working with SimpleXML to parse an XML document where the node name had a hyphen in it. I was finding a way to refer that element as a SimpleXMLElement and found a nifty note in PHP Manual. It says if you have unsupported (unsupported in PHP Lexicon for a variable name) characters inside the name of a node, you can access it using a special pattern {‘name’}.

So I tried the following code and it show that you can have a class variable named “i can have cheese burger”

$s = new stdClass();
$s->{'i can have cheese burger'} = "Oh Yeaaah";
echo $s->{'i can have cheese burger'}; //it will output "Oh Yeeah"

and if you print_f the object $s, you will see the following

stdClass Object
(
[i can have cheese burger] => Oh Yeeah
)

Well, Its funny! – I love having some fun writing PHP code!

17 replies on “did you know "you can have cheese burger" could be a variable name?”

That’s funny that you found this today as I stumbled across the same thing today by accident.

I was running a PostgreSQL query that aliased fields with meaningful names:

SELECT name AS “User Name”, …..

and did a var_dump() of pg_fetch_object() and noticed that the member variable had a space in it. Had no idea how to access it so I used a fetch assoc instead.

Oh no! While it might be neat to be able to do this.. can you image somone that like to have super long descriptive variables using this!?!?!??!?

Leave a Reply

Your email address will not be published. Required fields are marked *