Re: [RFC] Generalize support of negative string offsets
| From: | François Laupretre | Date: | Thu, 11 Feb 2016 13:30:32 +0000 |
| Subject: | Re: [RFC] Generalize support of negative string offsets | ||
| References: | 1 2 3 4 5 6 7 8 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-91206@lists.php.net to get a copy of this message | ||
Le 11/02/2016 13:46, Rowan Collins a écrit :
Christoph Becker wrote on 11/02/2016 12:16:In addition to string offsets, which will need to keep the same behavior for BC reasons, I had the idea of string 'ranges'. These could be expressed as 'str{<offset>:<length>}'. These 'ranges' would provide an alternate and more readable syntax for eveything you can do with substr() and substr_replace() : $str = "abc"; echo $str{0:2}; // -> "ab" $str{0:1} = 'xyz'; // -> "xyzbc" $str{-2:} = 'foo'; // -> "xyzfoo" $str{1:0} = 'bar'; // -> "xbaryzfoo" With such syntax, '$str{<offset>)' assignments would still take the first character only, and 'str{<offset>:1}' would replace the character with the whole string. Anyway, this is for another RFC. Thoughts ? Regards FrançoisAppending 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, and making it work *usefully*, rather than trying to make it look like arrays. Then, it would be less surprising for $string{-1} to behave differently from $array[-1], and that $string{} is a syntax error.