php 字符串 大括号,PHP中字符串的花括号

这篇博客详细介绍了PHP中的复杂语法,如使用花括号包裹表达式以在字符串中插入变量、对象属性和数组元素。文章通过多个示例展示了如何正确地在字符串中嵌入变量,并解释了为何需要使用花括号以及不使用花括号时可能出现的问题。同时,文中还提到了错误的用法以及注意事项,帮助读者理解并掌握这一语法特性。
摘要由CSDN通过智能技术生成

复杂(卷曲)语法

之所以称其为“复杂”,是因为语法复杂,而是因为它允许使用复杂的表达式。

可以通过此语法包括具有字符串表示形式的任何标量变量,数组元素或对象属性。只需以与出现在字符串外部相同的方式编写表达式,然后将其包装在{和中即可}。由于{无法转义,因此仅在$紧随其后的才会识别此语法{。使用

{\$得到文字{$。一些示例可以使您清楚:

// 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()}”;

?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值