php PHP中字符串中的花括号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2596837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Curly braces in string in PHP
提问by redcoder
What is the meaning of { }(curly braces) in string literals in PHP?
{ }PHP中字符串文字中的(花括号)是什么意思?
回答by cletus
This is the complex (curly) syntaxfor 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()}"; ?>
复杂(卷曲)语法
之所以称为复杂,不是因为语法很复杂,而是因为它允许使用复杂的表达式。
任何具有字符串表示形式的标量变量、数组元素或对象属性都可以通过此语法包含在内。只需按照它出现在字符串外部的相同方式编写表达式,然后将其包裹在
{和 中}。由于{无法转义,此语法仅$在{. 使用{\$得到文字{$。一些例子来说明:<?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:
将根据您的错误级别,要么不起作用,要么产生错误,因为没有名为 的变量$aefgh,因此您需要执行以下操作:
$out = "${a}efgh"; // or
$out = "{$a}efgh";
回答by Kredo900
As for me, curly braces serve as a substitution for concatenation, they are quickerto type and code looks cleaner. Remember to use double quotes (" ") as their content is parsedby PHP, because in single quotes (' ') you'll get the literal nameof 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
?>
回答by Obiware
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,但该变量不存在!
回答by Ray N. Franklin
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,
);
}
}
回答by user1232972
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.
这是格式化复杂字符串的非常方便的技术。

