为什么 PHP 不支持字符串中 const 的大括号扩展?

发布于 2024-09-29 23:40:44 字数 396 浏览 1 评论 0原文

PHP 支持这个:

$z = 5;
$str = "z is $z";  // result: "z is 5"

并且它支持这个:

$c = new StdClass();
$c->x = 9;
$str = "x is {$c->x}";  // result: "x is 9"

但它不支持这个:

class abc
{
   const n = 2;
}
$str = "x is {abc::n}";  // result: "x is {abc::n}"

为什么 PHP 支持通过大括号语法插入常量?看来应该...

PHP supports this:

$z = 5;
$str = "z is $z";  // result: "z is 5"

and it supports this:

$c = new StdClass();
$c->x = 9;
$str = "x is {$c->x}";  // result: "x is 9"

but it does NOT support this:

class abc
{
   const n = 2;
}
$str = "x is {abc::n}";  // result: "x is {abc::n}"

Why does PHP not support insertion of consts via the curly-brace syntax? Seems like it should...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

笙痞 2024-10-06 23:40:44

curly 语法是扩展的变量语法。它用于将变量插入字符串中。正如 PHP 中的变量以 $ 开头一样,其他所有内容都会产生语法错误。

但你可以做的是调用变量函数。因此你可以这样做:

$_ = function ($expr) { return $expr; };

echo "Something {$_(Class::Constant)}";

但这通常是不合适的。相反,请使用字符串连接:

echo 'Something ' . Class::Constant;

The curly syntax is the extended variable syntax. It is used to interpolate variables into strings. And as in PHP variables start with $ everything else will yield a syntax error.

But what you can do is call variable-functions. Thus you could do:

$_ = function ($expr) { return $expr; };

echo "Something {$_(Class::Constant)}";

But that's a hack which normally isn't appropriate. Instead please use string concatenation:

echo 'Something ' . Class::Constant;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文