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

推荐答案

这是字符串插值的complex (curly) syntax.从手册中:

复杂(curl )语法

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

任何带有字符串的标量变量、数组元素或对象属性

<?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()}";
?>

通常,此语法是不必要的.例如,这是:

$a = 'abcd';
$out = "$a $a"; // "abcd abcd";

行为与此完全相同:

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

所以没有必要用花括号.但是this:

$out = "$aefgh";

由于没有名为$aefgh的变量,根据您的错误级别,将不起作用或产生错误,因此您需要执行以下操作:

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

Php相关问答推荐

添加到购物车验证时获取WooCommerce分组产品ID

相同的数组(一个来自func_get_args(),另一个显式构建)在用作参数时并不相同

我的docker—compose lamp stack在软件更新后不工作:Containerconfig错误'''

自定义WooCommerce查询字符串仅显示前3个产品

从产品中获取WooCommerce产品属性单选按钮的列表WP_Query

Nginx重写扩展名为.php的动态URL

PHP测试字符串的所有POST值

如何从Laravel中的Spatie\Dns\Records\A对象中提取IP地址

使用ESI的Symfony Sulu清漆

WooCommerce中基于用户角色的不同产品差价

如果日期是过go 日期,则隐藏事件发布类型

启用 WooCommerce 我的帐户付款方式,允许客户添加付款方式

Woocommerce API - 图像问题

为什么从一个页面到另一个页面都找不到 JQuery,因为它们使用相同的 twig 模板?

Laravel 10 - 使用缓存对 ThrottleRequest 进行限制

根据页面的最后修订日期设置 MediaWiki 内部链接的样式

从 Laravel 机制中排除目录并直接访问该目录

如何在WooCommerce中为访客购买者分配自定义客户代码

带有 nginx 的 Symfony 不提供 .js 和 .css 文件

在 WooCommerce 结帐后更新用户元字段