PHP中的字符串中的大括号

时间:2010-04-08 00:35:01

标签: php string

PHP中字符串文字中{ }(花括号)的含义是什么?

5 个答案:

答案 0 :(得分:252)

这是字符串插值的complex (curly) syntax。从手册:

  

复杂(卷曲)语法

     

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

     

带字符串的任何标量变量,数组元素或对象属性   可以通过此语法包含表示。简单地写一下   表达式与字符串外部的表达方式相同,并且   然后将其包装在{}中。由于无法转义{,因此使用此语法   只有$紧跟{后才能识别。使用   {\$获取文字{$。一些例子说清楚:

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

通常,这种语法是不必要的。例如,这个:

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

的行为完全相同:

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

所以花括号是不必要的。但是这个

$out = "$aefgh";
根据你的错误级别,

会不起作用或产生错误,因为没有名为$aefgh的变量,所以你需要这样做:

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

答案 1 :(得分:46)

就我而言,花括号用作连接的替代,它们更快来键入,代码看起来更干净。请记住使用双引号(“”),因为PHP的内容被解析,因为在单引号('')中,您将获得提供的变量的文字名称

<?php

 $a = '12345';

// This works:
 echo "qwe{$a}rty"; // qwe12345rty, using braces
 echo "qwe" . $a . "rty"; // qwe12345rty, concatenation used

// Does not work:
 echo 'qwe{$a}rty'; // qwe{$a}rty, single quotes are not parsed
 echo "qwe$arty"; // qwe, because $a became $arty, which is undefined

?>

答案 2 :(得分:14)

示例:

$number = 4;
print "You have the {$number}th edition book";
//output: "You have the 4th edition book";

如果没有花括号,PHP会尝试找到一个名为$numberth的变量,该变量不存在!

答案 3 :(得分:3)

我还发现访问对象属性很有用,其中属性名称因某些迭代器而异。例如,我使用了下面的模式来表示一组时间段:小时,天,月。

$periods=array('hour', 'day', 'month');
foreach ($periods as $period)
{
    $this->{'value_'.$period}=1;
}

此相同模式也可用于访问类方法。只需使用字符串和字符串变量以相同的方式构建方法名称。

您可以轻易地争辩只是按周期使用数组来存储值。如果这个应用程序只是PHP,我会同意。当类属性映射到数据库表中的字段时,我使用此模式。虽然可以使用序列化将数组存储在数据库中,但是如果必须对各个字段建立索引,则效率低下并且没有意义。我经常添加一个由迭代器键入的字段名称数组,以实现两全其美。

class timevalues
{
                             // Database table values:
    public $value_hour;      // maps to values.value_hour
    public $value_day;       // maps to values.value_day
    public $value_month;     // maps to values.value_month
    public $values=array();

    public function __construct()
    {
        $this->value_hour=0;
        $this->value_day=0;
        $this->value_month=0;
        $this->values=array(
            'hour'=>$this->value_hour,
            'day'=>$this->value_day,
            'month'=>$this->value_month,
        );
    }
}

答案 4 :(得分:-5)

这是我从一个wordpress插件获得的代码

$data = $wpdb->get_results("select * from {$wpdb->prefix}download_monitor_files");

这对于格式化复杂字符串非常方便。

相关问题