Is undefined a data-type in php?-Collection of common programming errors
(might be a bit over the top)
Here are two fairly “simple” ways to mimic your own undefined type. With some overhead for a function call it can be available to your code without using the keyword global.
the output (PHP 5.3.23):
undef1 in string context : string(9) "undefined" // :)
undef1 in boolean context: bool(true) // :(
undef1 compared to itself: bool(true) // :)
undef2 in string context : string(0) "" // :( ?
undef2 in boolean context: bool(false) // :)
undef2 compared to itself: bool(true) // :)
In either case it seems ticky to get the thing to feel like JavaScript.
To get the object to evaluate to boolean false the second solution uses a hack with the way PHP handles SimpleXMLElement objects. However that same hack can backfire if some code alters the XML value of your undef2 object.
Sadly the magic function __toString() becomes ironically useless when extending the SimpleXMLElement class. Maybe there is another function to overload that will return a custom string but I cannot find it. Though maybe an empty string is actually more practical.
There are PECL operator overloads that could maybe get the undef1 class to evaluate to boolean false, but the extension is beta and might not be available to your PHP code.
Misc notes:
It seems that an undefined type would make a lot of sense for custom classes that implement ArrayAccess, where it is be possible to:
- ignore creation of elements if the $value === undefined
- return undefined if a key or index is not defined
In the example above the class is not restricted to a singleton. You can make it behave that way if you wish: Creating the Singleton design pattern in PHP5
Originally posted 2013-11-09 19:43:54.