在字符串表示之外使用复杂(花括号)语法的目的


Purpose of complex (curly) syntax outside a string representation

我理解字符串内复杂(花括号)语法的用法,但我不理解它在字符串外的目的。

我刚刚在CakePHP中发现了这段代码,我无法理解:

// $class is a string containg a class name
${$class} =& new $class($settings);

如果有人能帮助我理解为什么在这里使用,以及这和:

有什么区别?
$class =& new $class($settings);

谢谢。

理解这一点最简单的方法是通过示例:

class FooBar { }
// This is an ordinary string.
$nameOfClass = "FooBar";
// Make a variable called (in this case) "FooBar", which is the
// value of the variable $nameOfClass.
${$nameOfClass} = new $nameOfClass();
if(isset($FooBar))
    echo "A variable called FooBar exists and its class name is " . get_class($FooBar);
else
    echo "No variable called FooBar exists.";

使用${$something}$$something。在PHP中被称为"可变变量"。

因此,在本例中,创建了一个名为$FooBar的新变量,而变量$nameOfClass仍然只是一个字符串。

在字符串外部使用复杂(花括号)语法的一个例子是,当由多个变量组成的表达式形成变量名时。考虑下面的代码:

$first_name="John";
$last_name="Doe";
$array=['first','last'];
foreach ($array as $element) {
    echo ${$element.'_name'}.' ';
}

在上面的代码中,echo语句将在第一个循环期间输出变量$first_name的值,并在第二个循环期间输出变量$last_name的值。如果要删除花括号,echo语句将尝试在第一次循环中输出变量$first的值,在第二次循环中输出变量$last的值。但是由于没有定义这些变量,代码将返回一个错误。

第一个示例创建了一个动态命名的变量(name是类变量的值),另一个示例覆盖了类变量的值。