In the German channel #php.de/IRCNet people discuss every kind of stuff. Sometimes there are even discussions about PHP related topics. Today we had a discussion about having fun with casting in PHP.
My colleague Uwe asked wether PHP already supports object casting. Object casting could be used to convert an object returned from some function to an object from an extended class:
<?php
class Bar {
/* ... */
}
class Foo extends Bar {
/* ... */
}
function do_something() {
return new Bar();
}
$bar = do_something();
$foo = (Foo)$bar;
?>
Now $foo would be an object of the Foo class but such a casting is not (yet) supported by PHP. Nasty ideas to simulate it (Decorator pattern, classkit or some serialize-manipulate-unserialize-magic) didn’t please him.
As used from other places such discussions won’t stop then but develop into other directions. But taking a look at PHP casting options someone found the object cast operator. It can be used to convert some variable to a stdClass object. If the variable is a scalar the object gets a property "scalar" with the original value:
$ php -r '$a = 1; var_dump((object)$a);'<br />object(stdClass)#1 (1) {<br /> ["scalar"]=><br /> int(1)<br />}<br />
If you cast an array you get a stdClass object with the array’s keys as value:
$ php -r '$a = array("a" => 23, "b" => 42); var_Dump((object)$a);'<br />object(stdClass)#1 (2) {<br /> ["a"]=><br /> int(23)<br /> ["b"]=><br /> int(42)<br />}
This is followed by the question what happens with numeric keys since numbers aren’t valid property name? – Quite simple nothing special:
$ php -r '$a = array(23, 42); var_dump((object)$a);'<br />object(stdClass)#1 (2) {<br /> [0]=><br /> int(23)<br /> [1]=><br /> int(42)<br />}<br />
Now we have properties with integers as their name. Accessing them with $a->0 gives a parse error since this syntax isn’t allowed, but PHP offers another syntax for this: $a->{0} This even works for strings with invalid characters, like spaces or other weird stuff:
$ php -r '$a = array(" #<>" => 42); $b = (object)$a; echo $b->{" #<>"};'<br />42
This is fun but that’s not everything you can do with PHP’s casting syntax: PHP does even support an unset cast operator (unset). The array to object cast might sometimes make sense but we have no clue why a cast to unset is needed.
$ php -r '$bar = 1; $foo = (unset)$bar; var_dump(isset($foo));'<br />bool(false)
Now $foo is unset but $bar is still 1. Using unset() on a variable makes sense but casting some value to unset? Is it just a strange way to do unset($foo);?
But i am curious: Please leave a comment if you can think of an situation where (unset) might actually make sense.
Schreibe einen Kommentar