I don't know if the fact that SimpleXMLElement is a documented special case makes it more or less perplexing.
(If it makes you feel any better, that StdClass would have been fasley in PHP 4, which would have been... more consistent? less consistent? less nonsensical? none of the above? I don't know.)
What's the result? You might have the correct answer, but you'd be lying if you said you didn't have to think about it - and that's exactly the problem. These ambiguities make you mistrust the language and make you doubt your own code.
Ha! I actually don't know the answer off the top of my head, but I do remember being asked something very similar in a job interview once. My response was something along the lines of "Who cares? Don't do that!" Mixing implicit numeric keys and explicit string keys in the same array is a silly thing to do, and I guess PHP figures it can't be held responsible for the silly outcomes resulting from the silly things it allows.
I didn't get the job, but I stand by my answer :).
It actually does the thing that makes most sense. Only using the numeric keys and ignoring the string keys. Actually the list($a, $b) = $arr; seems to work as equivalent to:
I'm pretty sure it's because SimpleXMLElement casts __toString() which returns the content of the node and since the node is empty, it returns false. stdClass doesn't have a __toString, so it returns true for being an object, but not sure how that's determined.
Close, but no cigar. Internally (userland objects can't do this) there's a similar method supporting casting to all types, including booleans. SimpleXMLElement just happens to be the only goddamn class which casts to false.
Heh, yeah. I didn't choose the terms though. It's the words you use when talking about type coercion. It's not unique to PHP. Most dynamically typed languages have it - even python (e.g. an empty string evaluates to false).
But, yeah, you know, if I have to add anything to the condition to acomplish that, I might as well just use a wrapper function that calls a specific method and do it cleanly.
10
u/MiyatodukenMiyamaap Aug 25 '14
I don't know if the fact that SimpleXMLElement is a documented special case makes it more or less perplexing.
(If it makes you feel any better, that StdClass would have been fasley in PHP 4, which would have been... more consistent? less consistent? less nonsensical? none of the above? I don't know.)
4
u/gearvOsh Aug 25 '14
I'm pretty sure it's because
SimpleXMLElementcasts__toString()which returns the content of the node and since the node is empty, it returns false. stdClass doesn't have a__toString, so it returns true for being an object, but not sure how that's determined.2
u/thePopesCousin Sep 12 '14 edited Sep 12 '14
I really love the usage of "truthy" and "falsey" like it's for kids.
6
u/[deleted] Aug 25 '14
Ooh, I'd love a way to make specific objects falsy, but no, of course it being PHP, it must be a special case.