简体   繁体   中英

PHP curly braces in array notation

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?

It is mentioned in the manual. {} is just an alternative syntax to [] § Accessing array elements with square bracket syntax . This method is deprecated as of PHP 7.4.0 and no longer supported as of PHP 8.0.0.

Note:

Prior to PHP 8.0.0, square brackets and curly braces could be used interchangeably for accessing array elements (eg $array[42] and $array{42} would both do the same thing in the example above). The curly brace syntax was deprecated as of PHP 7.4.0 and no longer supported as of PHP 8.0.0.

The same goes the strings § String access and modification by character :

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: Prior to PHP 8.0.0, strings could also be accessed using braces, as in $str{42}, for the same purpose. This curly brace syntax was deprecated as of PHP 7.4.0 and no longer supported as of PHP 8.0.0.

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.

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.

Curly braces as of PHP 7.4 are deprecated for accessing arrays.

https://wiki.php.net/rfc/deprecate_curly_braces_array_access

PHP7.4正式弃用使用花括号访问数组和字符串偏移量 Ref: https://www.php.net/manual/en/migration74.deprecated.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM