On Thu, Feb 11, 2016 at 1:46 PM, Rowan Collins <rowan.coll...@gmail.com>
wrote:

> Christoph Becker wrote on 11/02/2016 12:16:
>
>> Appending to an array always adds a single element only, consider
>>
>>    $a = [1,2,3];
>>    $a[] = [4,5];
>>
>> The suggested syntax for strings would concatenate an arbitrary amount
>> of elements (characters) to a string.  IMHO, this would not be
>> consistent, but rather confusing.  The alternative interpretation to
>> append the first character only, would be confusing as well (besides
>> there would be issues with regard to multibyte character encodings).
>>
>
> Indeed, this is a big problem with making the string offset functionality
> richer in general, because PHP has no "char" type, only a single-character
> string. This leads to some odd things:
>
> // string[0] returns a one-char string, which has an element [0], so you
> can keep adding [0] for as long as you like:
> $foo = 'abc';
> echo $foo[0][0][0][0][0]; // a
>
> // assignment to an offset only overwrites one character, but the source
> can be a string of any length:
> $foo = 'abc';
> $foo[0] = 'zzz';
> echo $foo; // zbc
>
> String offsets simply can't behave like array offsets within PHP's current
> type system, which is why I favour dedicating {} syntax to them


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.

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. 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.

Similarly, Stas' comments on how things like $string[0] ^= "\xf0" do no
work, are not a reason to promote a different string offset syntax -- that
wouldn't actually *solve* anything. Instead we should strive to make these
things work as expected. If I can write $string[0] = $string[0] ^ "\xf0" it
stands to reason that $string[0] ^= "\xf0" should work as well.

Nikita

Reply via email to