What is the meaning of { }
(curly braces) in string literals in PHP?
在PHP字符串中,{}(花括号)的含义是什么?
5 个解决方案
#1
221
This is the complex (curly) syntax for string interpolation. From the manual:
这是字符串插值的复杂(卷曲)语法。从手册:
Complex (curly) syntax
This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.
这并不是因为语法是复杂的,而是因为它允许使用复杂的表达式。
Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in
{
and}
. Since{
can not be escaped, this syntax will only be recognised when the$
immediately follows the{
. Use{\$
to get a literal{$
. Some examples to make it clear:任何具有字符串表示形式的标量变量、数组元素或对象属性都可以通过此语法包含。只需以与字符串外显示相同的方式编写表达式,然后将其封装为{和}。由于无法转义{,因此只有当$紧跟在{之后时才能识别此语法。使用{\$获取一个文字{$。有一些例子可以说明这一点:
<?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()}"; ?>
Often, this syntax is unnecessary. For example, this:
通常,这种语法是不必要的。例如,这个:
$a = 'abcd';
$out = "$a $a"; // "abcd abcd";
behaves exactly the same as this:
行为与此完全相同:
$out = "{$a} {$a}"; // same
So the curly braces are unnecessary. But this:
所以大括号是不必要的。但这:
$out = "$aefgh";
will, depending on your error level, either not work or produce an error because there's no variable named $aefgh
, so you need to do:
will,根据您的错误级别,不会工作或产生错误,因为没有名为$aefgh的变量,所以您需要:
$out = "${a}efgh"; // or
$out = "{$a}efgh";
#2
40
As for me, curly braces serve as a substitution for concatenation, they are quicker to type and code looks cleaner. Remember to use double quotes (" ") as their content is parsed by PHP, because in single quotes (' ') you'll get the literal name of variable provided:
对于我来说,花括号可以作为连接的替代,它们更容易输入,代码看起来更简洁。记住要使用双引号(" "),因为它们的内容是由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
?>
#3
14
Example:
例子:
$number = 4;
print "You have the {$number}th edition book";
//output: "You have the 4th edition book";
Without curly braces PHP would try to find a variable named $numberth
, that doesn't exist!
如果没有花括号,PHP会尝试找到一个名为$numberth的变量,它根本不存在!
#4
2
I've also found it useful to access object attributes where the attribute names vary by some iterator. For example, I have used the pattern below for a set of time periods: hour, day, month.
我还发现,访问属性名称因迭代器而异的对象属性非常有用。例如,我将下面的模式用于一组时间段:小时、天、月。
$periods=array('hour', 'day', 'month');
foreach ($periods as $period)
{
$this->{'value_'.$period}=1;
}
This same pattern can also be used to access class methods. Just build up the method name in the same manner, using strings and string variables.
同样的模式也可以用于访问类方法。只需使用字符串和字符串变量以相同的方式构建方法名。
You could easily argue to just use an array for the value storage by period. If this application were PHP only, I would agree. I use this pattern when the class attributes map to fields in a database table. While it is possible to store arrays in a database using serialization, it is inefficient, and pointless if the individual fields must be indexed. I often add an array of the field names, keyed by the iterator, for the best of both worlds.
您可以很容易地认为,只需使用一个数组,就可以按周期使用值存储。如果这个应用程序只是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,
);
}
}
#5
-5
here is the code I got from one wordpress plugin
这是我从wordpress插件中得到的代码
$data = $wpdb->get_results("select * from {$wpdb->prefix}download_monitor_files");
This is really handy technique for formatting complex strings.
这对于格式化复杂的字符串非常方便。
#1
221
This is the complex (curly) syntax for string interpolation. From the manual:
这是字符串插值的复杂(卷曲)语法。从手册:
Complex (curly) syntax
This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.
这并不是因为语法是复杂的,而是因为它允许使用复杂的表达式。
Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in
{
and}
. Since{
can not be escaped, this syntax will only be recognised when the$
immediately follows the{
. Use{\$
to get a literal{$
. Some examples to make it clear:任何具有字符串表示形式的标量变量、数组元素或对象属性都可以通过此语法包含。只需以与字符串外显示相同的方式编写表达式,然后将其封装为{和}。由于无法转义{,因此只有当$紧跟在{之后时才能识别此语法。使用{\$获取一个文字{$。有一些例子可以说明这一点:
<?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()}"; ?>
Often, this syntax is unnecessary. For example, this:
通常,这种语法是不必要的。例如,这个:
$a = 'abcd';
$out = "$a $a"; // "abcd abcd";
behaves exactly the same as this:
行为与此完全相同:
$out = "{$a} {$a}"; // same
So the curly braces are unnecessary. But this:
所以大括号是不必要的。但这:
$out = "$aefgh";
will, depending on your error level, either not work or produce an error because there's no variable named $aefgh
, so you need to do:
will,根据您的错误级别,不会工作或产生错误,因为没有名为$aefgh的变量,所以您需要:
$out = "${a}efgh"; // or
$out = "{$a}efgh";
#2
40
As for me, curly braces serve as a substitution for concatenation, they are quicker to type and code looks cleaner. Remember to use double quotes (" ") as their content is parsed by PHP, because in single quotes (' ') you'll get the literal name of variable provided:
对于我来说,花括号可以作为连接的替代,它们更容易输入,代码看起来更简洁。记住要使用双引号(" "),因为它们的内容是由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
?>
#3
14
Example:
例子:
$number = 4;
print "You have the {$number}th edition book";
//output: "You have the 4th edition book";
Without curly braces PHP would try to find a variable named $numberth
, that doesn't exist!
如果没有花括号,PHP会尝试找到一个名为$numberth的变量,它根本不存在!
#4
2
I've also found it useful to access object attributes where the attribute names vary by some iterator. For example, I have used the pattern below for a set of time periods: hour, day, month.
我还发现,访问属性名称因迭代器而异的对象属性非常有用。例如,我将下面的模式用于一组时间段:小时、天、月。
$periods=array('hour', 'day', 'month');
foreach ($periods as $period)
{
$this->{'value_'.$period}=1;
}
This same pattern can also be used to access class methods. Just build up the method name in the same manner, using strings and string variables.
同样的模式也可以用于访问类方法。只需使用字符串和字符串变量以相同的方式构建方法名。
You could easily argue to just use an array for the value storage by period. If this application were PHP only, I would agree. I use this pattern when the class attributes map to fields in a database table. While it is possible to store arrays in a database using serialization, it is inefficient, and pointless if the individual fields must be indexed. I often add an array of the field names, keyed by the iterator, for the best of both worlds.
您可以很容易地认为,只需使用一个数组,就可以按周期使用值存储。如果这个应用程序只是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,
);
}
}
#5
-5
here is the code I got from one wordpress plugin
这是我从wordpress插件中得到的代码
$data = $wpdb->get_results("select * from {$wpdb->prefix}download_monitor_files");
This is really handy technique for formatting complex strings.
这对于格式化复杂的字符串非常方便。