PHP 中的裸字符串是否有任何合法用途? [英] Is there any legitimate use for bare strings in PHP?

查看:39
本文介绍了PHP 中的裸字符串是否有任何合法用途?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题让我想到了裸字符串.

当 PHP 看到一个没有用引号括起来的字符串时,它首先检查它是否是一个常量.如果不是,它只是假设它是一个字符串,然后继续.例如,如果我有

When PHP sees a string that's not enclosed in quotes, it first checks to see if it's a constant. If not, it just assumes it's a string and goes on anyway. So for example if I have

echo $foo[bar];

如果有一个名为 bar 的常量,它会将它用作数组键,但如果没有,则它将 bar 视为一个裸字符串,因此它的行为就像

If there's a constant called bar it uses that for the array key, but if not then it treats bar as a bare string, so it behaves just like

echo $foo["bar"];

如果在未来某个日期添加同名常量,这可能会导致各种问题.

This can cause all kinds of problems if at some future date a constant is added with the same name.

我的问题是,在任何情况下使用裸字符串是否真的有意义?

My question is, is there any situation in which it actually makes sense to use a bare string?

推荐答案

不,我看不到一个有意义的实例,而且它总是很危险.绝对应该保留使用不带引号的字符串来处理常量.我完全不明白 PHP 的发明者是如何决定引入这种荒谬的行为的——这使得正确使用常量几乎是不可能的(因为如果你试图访问一个尚未定义的常量,PHP 会默默地、愚蠢地生成一个字符串)而不给任何好处.

Nope, I can not see a single instance where it would make sense, and it always is dangerous. Using strings without quotes should absolutely be reserved to address constants. I don't understand how the inventors of PHP could decide to introduce this ridiculous behaviour at all - it makes the proper use of constants almost impossible (because if you try to access a constant that has not been defined, PHP will silently and stupidly generate a string) without giving any benefit.

这篇关于PHP 中的裸字符串是否有任何合法用途?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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