PHP中字符串的花括号

qyyhg6bp  于 2022-11-28  发布在  PHP
关注(0)|答案(4)|浏览(139)

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

2ledvvac

2ledvvac1#

这是字符串插值的复杂( curl )语法。来自手册:

复杂( curl )语法

之所以称之为复杂,并不是因为语法复杂,而是因为它允许使用复杂表达式。
任何标量变量、数组元素或对象属性都可以通过此语法包含在字符串中。只需按照在字符串外出现的方式编写表达式,然后将其 Package 在{}中。由于{不能转义,仅当$紧跟在{之后时,才能识别此语法。使用{\$可获取文字{$。下面的示例可使您更清楚地了解此语法:

<?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

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

$out = "$aefgh";

根据您的错误级别,将无法工作或产生错误,因为没有名为$aefgh的变量,因此您需要执行以下操作:

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

cbwuti442#

对我来说,花括号可以代替连接,它们输入起来更快,代码看起来更干净。记住使用双引号(““),因为它们的内容会被PHP解析,因为在单引号(' ')中你会得到 * a提供的变量的文本名称

<?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

?>
uidvcgyl

uidvcgyl3#

示例:

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

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

a64a0gku

a64a0gku4#

我还发现,访问对象属性(属性名称因迭代器而异)也很有用。例如,我对一组时间段使用了下面的模式:时、日、月。

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

同样的模式也可以用来访问类方法,只需要用字符串和字符串变量以同样的方式建立方法名即可。
您可以很容易地主张只使用一个数组来按句点存储值。如果这个应用程序只是PHP,我会同意。当类属性Map到数据库表中的字段时,我使用这种模式。虽然可以使用序列化在数据库中存储数组,但如果必须对单个字段进行索引,则效率很低,而且毫无意义。我经常添加一个字段名数组,以迭代器为键。为了两全其美。

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,
        );
    }
}

相关问题