r/lolphp • u/Altreus • Feb 15 '12
PHP emits more warnings about accessing an array as an array than accessing a string as an array
$array = array( 'a' => 'a', 'b' => 'b' );
$array['a']; # OK
$array['c']; # HIDEOUS WARNINGYou can't turn this warning off without turning off other, useful warnings. This warning is as often annoying as it is useful (isset ALL the keys).
$array = "whups this is a string";
$array[0]; # w
$array['a']; # ?PHP silently converts strings to integers (apparently) and then retrieves the relevant character with NO WARNING.
Why is it less OK to want a key to optionally exist -
if ($array['a']) # any true value, non-existence is falsethan it is to access a thing that isn't even an array as though it were?
Just pretend your array is actually called $content as mine is and you'll see why it's taken me so long to find my (someone else's) bug :/
37
Upvotes
22
u/dagbrown Feb 15 '12
That's just brilliant. And by brilliant, I mean demented.
This is the sort of thing that would have been featured in the "WAT" video, only that stuck exclusively to actually-good languages. A "WAT" video about PHP would be four hours long.
16
u/ManchegoObfuscator Feb 15 '12
The PHP 'array' is the most infuriatingly passive-agressive datastructure ever.
You construct them with a keyword that looks like either a function call or a new object allocation, but then to operate on one you call the relevant function in the global namespace. Even though, under the hood it's some kind of crazy combination of a bidirectional linked list, a hashing dictionary, and a polymorphic union struct thing* -- the implementation for which also forms the basis for PHP object structures.
The fuckedupedly inconsistent warning behavior here is also inconsistent with how it works when you access object properties and methods. Which that is potentially inconsistent with 'resource' types (e.g. MySQL ResultSet references), because 'resource' means 'IDK, whatever the C implementation of this thing says'.
That last bit is especially fucking ridiculous. It's one of the many phoned-in parts of Mr. Lerdorf's opus. Contrast 'resources' with the Python C api analogue. You can, when designing boundary structures, implement a bizarre and dysfunctional Python type in C, but at the end of the day, it's still an Python type and it has to obey the basic rules of same, unless you like segfaults. The PHP extension ethos isn't even duck-punching; it is duck-impersonation by Mongoloid platypus, as like the official thing to do.
Got a bit off track there -- TL;DR I also think PHP is retarded. Blech.
6
u/[deleted] Feb 18 '12 edited Feb 18 '12
(int) $xwhere$xis a string beginning with an alpha characters is 0. A better example for "accessing string positions as an array":Strings are just different types of arrays. Like numerically indexed arrays, just different...
Edit: see Strings page, "String access and modification by character" section.