代码之家  ›  专栏  ›  技术社区  ›  zildjohn01

PHP卷曲字符串语法问题

php
  •  4
  • zildjohn01  · 技术社区  · 14 年前

    我在运行php 5.3.0。我发现只有当表达式的第一个字符是 $ . 是否有方法包括其他类型的表达式(函数调用等)?

    简单的例子:

    <?php
    $x = '05';
    echo "{$x}"; // works as expected
    echo "{intval($x)}"; // hoped for "5", got "{intval(05)}"
    
    5 回复  |  直到 12 年前
        1
  •  2
  •   Ignacio Vazquez-Abrams    14 年前

    不可以。只有不同形式的变量才能用变量替换。

        2
  •  3
  •   Davor Lucic    14 年前
    <?php
    $x = '05';
    echo "{$x}";
    $a = 'intval';
    echo "{$a($x)}";
    ?>
    
        3
  •  2
  •   Justin Gregoire    14 年前

    看看这个链接 LINK

    代码示例,

    Similarly, you can also have an array index or an object property parsed. With array indices, the closing square bracket (]) marks the end of the index. For object properties the same rules apply as to simple variables, though with object properties there doesn't exist a trick like the one with variables.
    
    <?php
    // These examples are specific to using arrays inside of strings.
    // When outside of a string, always quote your array string keys 
    // and do not use {braces} when outside of strings either.
    
    // Let's show all errors
    error_reporting(E_ALL);
    
    $fruits = array('strawberry' => 'red', 'banana' => 'yellow');
    
    // Works but note that this works differently outside string-quotes
    echo "A banana is $fruits[banana].";
    
    // Works
    echo "A banana is {$fruits['banana']}.";
    
    // Works but PHP looks for a constant named banana first
    // as described below.
    echo "A banana is {$fruits[banana]}.";
    
    // Won't work, use braces.  This results in a parse error.
    echo "A banana is $fruits['banana'].";
    
    // Works
    echo "A banana is " . $fruits['banana'] . ".";
    
    // Works
    echo "This square is $square->width meters broad.";
    
    // Won't work. For a solution, see the complex syntax.
    echo "This square is $square->width00 centimeters broad.";
    ?>
    

    有不同的事情,你可以实现与卷曲大括号,但它是有限的,取决于你如何使用它。

        4
  •  0
  •   Timothy    14 年前
    <?php
    class Foo
    {
        public function __construct() {
            $this->{chr(8)} = "Hello World!";
        }
    }
    
    var_dump(new Foo());
    
        5
  •  0
  •   Marc B    14 年前

    通常,您不需要在变量周围加大括号,除非您需要强制PHP将某个对象视为变量,否则它的常规解析规则可能不需要。大的是多维数组。PHP的解析器不贪婪地决定什么是变量,什么不是变量,因此需要大括号来强制PHP查看数组元素的其余引用:

    <?php
    
    $arr = array(
        'a' => array(
             'b' => 'c'
        ), 
    );
    
    print("$arr[a][b]"); // outputs:  Array[b]
    print("{$arr[a][b]}"); // outputs: (nothing), there's no constants 'a' or 'b' defined
    print("{$arr['a']['b']}"); // ouputs: c