Rowan Collins wrote: > Yasuo Ohgaki wrote on 09/06/2015 11:44: >> $v = NULL; >> $v[0][1][2][3][4][5][6][7][8][9]; // NULL >> >> this code is semantically wrong and I would like to have error/exception >> for such >> erroneous codes. > > PHP considers an uninitialised variable to have the value NULL, and a > NULL value to be coercable to any type, so this breaks down (logically, > not necessarily literally) as follows: > > - coerce $v to array() > - instantiate $v[0] as NULL > - coerce $v[0] to array() > - instantiate $v[0][1] as NULL > - and so on... > > Raising a notice whenever the type is coerced would be inconsistent with > other coercions (e.g. $foo = null; echo $foo + 1;). Raising a notice > whenever the coerced array is actually accessed would result in a notice > for every dimension, which would be very noisy. > > Ideally, it would give a single notice, as in the below, but I'm not > sure how that would be implemented: > > $v = array(); > var_dump($v[0][1][2][3][4][5][6][7][8][9]); > // Notice: Undefined index: 0 > // NULL > > Note that this is all rather different from the original case, which was > about values which *cannot be coerced to array*.
I wonder where these coercion rules are described. The manual has a section about "Converting to array"[1] which actually describes casting, and is obviously not what is happening when the subscript operator (as the langspec calls it[2]) is applied to non-null scalars. The section "Accessing array elements with square bracket syntax"[3] doesn't describe the behavior of accessing elements of non-arrays at all. The language specification specifies as constraint: | If subscript-expression is used in a non-lvalue context, the element | being designated must exist. Finally, it is not even clear why a value should be coerced to array when the subscript operator is applied – it might be coerced to string as well. [1] <http://php.net/manual/en/language.types.array.php#language.types.array.casting> [2] <https://github.com/php/php-langspec/blob/master/spec/10-expressions.md#subscript-operator> [3] <http://php.net/manual/en/language.types.array.php#language.types.array.syntax.accessing> -- Christoph M. Becker -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php