PHP中的字符串大括号 [英] Curly braces in string in PHP

查看:193
本文介绍了PHP中的字符串大括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the meaning of { } (curly braces) in string literals in PHP?

推荐答案

这是

复杂(卷曲)语法

之所以称为复杂不是因为语法复杂,而是因为 它允许使用复杂的表达式.

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";

与此完全相同:

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

因此不需要花括号.但是 this :

So the curly braces are unnecessary. But this:

$out = "$aefgh";

根据您的错误级别,可能不起作用或产生错误,因为没有名为$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:

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

这篇关于PHP中的字符串大括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆