PHP curly braces in array notation

若如初见. 提交于 2019-11-26 11:28:54

问题


I\'d just come across a very weird bit of php code:

$oink{\'pig\'} = 1;
var_dump($oink);

$oink{\'pig\'} = \'123123\';
echo $oink{\'pig\'}; /* => 123123 */
echo $oink[\'pig\']; /* => 123123 */

It works like an array, but nowhere mentioned in the manual. What is this?


回答1:


It is mentioned in the manual. {} is just an alternative syntax to [] §:

Both square brackets and curly braces can be used interchangeably for accessing array elements (e.g. $array[42] and $array{42} will both do the same thing in the example above).

The same goes the strings §:

Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42]. Think of a string as an array of characters for this purpose. [...]

Note: Strings may also be accessed using braces, as in $str{42}, for the same purpose.




回答2:


According to this comment on the documentation, it is just another notation, probably designed to resemble the Perl syntax: http://www.php.net/manual/de/language.types.array.php#99015

Update: When this answer was originally posted, the PHP manual did not have any official information on this notation. By 2014, however, the comment referenced above had been removed and, as Pacerier's answer says, the notation has been given official mention in the manual.




回答3:


It is mentioned in the manual, but it's obscure:

http://www.php.net/manual/en/language.types.string.php#language.types.string.substr

In a nutshell, the curly braces access only a single character (try adding a full string and you'll see it returns only the first character). It is also deprecated, so I would avoid it's use.



来源:https://stackoverflow.com/questions/8092248/php-curly-braces-in-array-notation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!