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

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

问题描述

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

What is the meaning of { } (curly braces) in string literals in 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";

行为与此完全相同:

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

所以花括号是不必要的.但是这个:

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天全站免登陆