【问题标题】:Difference between the open/close curly brace instead of open/close double quote to interpret a string in PHP打开/关闭花括号而不是打开/关闭双引号在 PHP 中解释字符串的区别
【发布时间】:2026-02-02 12:20:03
【问题描述】:

我阅读了 PHP 手册,但并不清楚其中有什么区别。我很困惑使用这个有什么意义:

echo "Print this {$test} here.";

与此相比:

echo "Print this $test here.";

【问题讨论】:

    标签: php curly-braces


    【解决方案1】:

    在您的示例中,没有区别。但是,当变量表达式更复杂时,它会很有帮助,比如带有字符串索引的数组。例如:

    $arr['string'] = 'thing';
    
    echo "Print a {$arr['string']}";
    // result: "Print a thing";
    
    echo "Print a $arr['string']";
    // result: Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE
    

    【讨论】:

      【解决方案2】:

      来自PHP.net

      复杂(卷曲)语法

      这不是因为语法复杂,而是因为 它允许使用复杂的表达式。

      任何标量变量、数组元素或带有字符串的对象属性 可以通过此语法包含表示。简单地写 表达方式与它出现在字符串之外的方式相同,并且 然后将其包装在 { 和 } 中。由于 { 无法转义,因此此语法将 仅当 $ 紧跟 { 时才被识别。使用 {\$ 来 得到一个字面量 {$.

      例子:

      <?php
      // Show all errors
      error_reporting(E_ALL);
      
      $great = 'fantastic';
      
      // Won't work, outputs: This is { fantastic}
      echo "This is { $great}";
      
      // Works, outputs: This is fantastic
      echo "This is {$great}";
      echo "This is ${great}";
      
      // Works
      echo "This square is {$square->width}00 centimeters broad."; 
      
      
      // Works, quoted keys only work using the curly brace syntax
      echo "This works: {$arr['key']}";
      
      
      // Works
      echo "This works: {$arr[4][3]}";
      
      // This is wrong for the same reason as $foo[bar] is wrong  outside a string.
      // In other words, it will still work, but only because PHP first looks for a
      // constant named foo; an error of level E_NOTICE (undefined constant) will be
      // thrown.
      echo "This is wrong: {$arr[foo][3]}"; 
      
      // Works. When using multi-dimensional arrays, always use braces around arrays
      // when inside of strings
      echo "This works: {$arr['foo'][3]}";
      
      // Works.
      echo "This works: " . $arr['foo'][3];
      
      echo "This works too: {$obj->values[3]->name}";
      
      echo "This is the value of the var named $name: {${$name}}";
      
      echo "This is the value of the var named by the return value of getName(): {${getName()}}";
      
      echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";
      
      // Won't work, outputs: This is the return value of getName(): {getName()}
      echo "This is the return value of getName(): {getName()}";
      ?>
      

      有关更多示例,请参见该页面。

      【讨论】:

        最近更新 更多