PHP parser: braces around variables

后端 未结 3 1346
清酒与你
清酒与你 2021-01-05 13:30

I was wondering, how is the semantics of braces exactly defined inside PHP? For instance, suppose we have defined:

$a = \"foo\";

then what

相关标签:
3条回答
  • 2021-01-05 14:03

    The brackets delimit where the variable name ends; this example should speak for itself.

    $a = "hi!"
    
    echo "$afoo";  //$afoo is undefined
    
    echo "${a}foo";  //hi!foo
    
    echo "{$a}foo";  //hi!foo
    

    Also, this should spit out a warning; you should use

    ${'a'}
    

    Otherwise it will attempt to assume a is a constant.

    0 讨论(0)
  • 2021-01-05 14:11

    Also you can use braces to get Char in the position $i of string $text:

    $i=2;
    $text="safi";

    echo $text{$i}; // f

    0 讨论(0)
  • 2021-01-05 14:12

    There are a lot of possibilities for braces (such as omitting them), and things get even more complicated when dealing with objects or arrays.

    I prefer interpolation to concatenation, and I prefer to omit braces when not necessary. Sometimes, they are.

    You cannot use object operators with ${} syntax. You must use {$...} when calling methods, or chaining operators (if you have only one operator such as to get a member, the braces may be omitted).

    The ${} syntax can be used for variable variables:

    $y = 'x';
    $x = 'hello';
    echo "${$y}"; //hello
    

    The $$ syntax does not interpolate in a string, making ${} necessary for interpolation. You can also use strings (${'y'}) and even concatenate within a ${} block. However, variable variables can probably be considered a bad thing.

    For arrays, either will work ${foo['bar']} vs. {$foo['bar']}. I prefer just $foo[bar] (for interpolation only -- outside of a string bar will be treated as a constant in that context).

    0 讨论(0)
提交回复
热议问题