Curly braces in string in PHP

后端 未结 5 723
刺人心
刺人心 2020-11-21 23:13

What is the meaning of { } (curly braces) in string literals in PHP?

5条回答
  •  逝去的感伤
    2020-11-21 23:41

    This is the complex (curly) syntax for string interpolation. From the manual:

    Complex (curly) syntax

    This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.

    Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$. Some examples to make it clear:

    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()}";
    ?>
    

    Often, this syntax is unnecessary. For example, this:

    $a = 'abcd';
    $out = "$a $a"; // "abcd abcd";
    

    behaves exactly the same as this:

    $out = "{$a} {$a}"; // same
    

    So the curly braces are unnecessary. But this:

    $out = "$aefgh";
    

    will, depending on your error level, either not work or produce an error because there's no variable named $aefgh, so you need to do:

    $out = "${a}efgh"; // or
    $out = "{$a}efgh";
    

提交回复
热议问题