简体   繁体   English

PHP中字符串中的花括号

[英]Curly braces in string in PHP

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

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:将根据您的错误级别,要么不起作用,要么产生错误,因为没有名为$aefgh的变量,因此您需要执行以下操作:

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

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

?>

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的变量,但该变量不存在!

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.如果这个应用程序只是 PHP,我会同意。 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.为了两全其美,我经常添加一个由迭代器键控的字段名称数组。

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

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. 这是格式化复杂字符串的便捷技术。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM