Nikita Popov wrote on 11/02/2016 13:14:
The issue here is not an inherent problem with string offsets, it's simply yet another artifact of PHP's overly lenient nature. If I create an IntArray class that implements ArrayAccess, I don't think you would be much surprised if doing $intArray[$i] = "123abc" would end up storing the value int(123), as this just conforms to PHP's usual silent, lossy type conversion semantics. It's the same with string offsets, just with the conversion happening from string to single-character-string.
Eh, I can see the logic, but there is no such type as "single-character string"; that's why I said PHP's type system was to blame - if there was a "char" type, things become simpler to explain: - the assignment case would be a case of implicit conversion from string to char - the $foo[0][0] case could give an error that you can't offset a char, and "$bar = $foo[0]; echo $bar[0];" would be able to give the same error
I'd like to stress that these are just a couple of examples; I'm sure there are other "anomalies".
Just having a different syntax, writing $foo{0} = 'zzz' instead of $foo[0] = 'zzz' does not make the implicit truncation behavior any more obvious or reasonable.
No, but it gives a general warning to the reader that this is a bit like array access, but not quite.
If we want to actually make it less confusing, what we should do is throw a warning if such a truncation occurs. And that's something that can be done independently of syntax.
Agreed.
Instead we should strive to make these things work as expected.
Agreed for the cases where it is obvious what is expected. Sometimes, though, I think it is not reasonable to expect the same behaviour as for an array, and so "striving to make string offsets work well" and "striving to make string offsets work the same as array offsets" are different, and possibly conflicting, goals.
Regards, -- Rowan Collins [IMSoP] -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php