简体   繁体   English

这个PHP语法是什么意思?

[英]What does this PHP syntax mean?

Consider the code: 考虑一下代码:

$a = "foobar";
echo $a{3}; // prints b

I know $a[3] is 'b' but how come using {} in place of [] produec the same result ? 我知道$a[3]'b'但是如何使用{}代替[] produec得到相同的结果?

You can read here in official documentation about braces: 您可以在官方文档中阅读有关大括号的内容:

String s may also be accessed using braces, as in $str{42}, for the same purpose. 为了相同的目的,也可以使用大括号访问字符串,如$ str {42}。 However, this syntax is deprecated as of PHP 5.3.0. 但是,从PHP 5.3.0开始,不推荐使用此语法。 Use square brackets instead, such as $str[42]. 请改用方括号,例如$ str [42]。

EDIT This thread may interest you: "dropping curly braces" 编辑这个主题可能会让你感兴趣: “丢大括号”

It's just an alternative syntax; 它只是一种替代语法; the two forms compile to exactly the same bytecode: 这两个表单编译为完全相同的字节码:

<?php
$str = "aaab";
echo $str{3}; 
echo $str[3]; 
number of ops:  9
compiled vars:  !0 = $str
line     # *  op                           fetch          ext  return  operands
---------------------------------------------------------------------------------
   2     0  >   EXT_STMT                                                 
         1      ASSIGN                                                   !0, 'aaab'
   3     2      EXT_STMT                                                 
         3      FETCH_DIM_R                                      $1      !0, 3
         4      ECHO                                                     $1
   4     5      EXT_STMT                                                 
         6      FETCH_DIM_R                                      $2      !0, 3
         7      ECHO                                                     $2
         8    > RETURN                                                   1

它是相同的,但从PHP 5.3开始不推荐使用{}语法。

{} and [] are the same. {}和[]是一样的。 it is your choice what to use. 它是您的选择使用方法。 [] is more common though. []更常见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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