未转义的美元符号不会引发错误; PHP 处理边缘情况?

发布于 2024-12-27 05:01:23 字数 612 浏览 4 评论 0原文

我在 PHP 处理器中遇到了一个看似奇怪的边缘情况。根据 PHP 手册:

PHP 中的变量由美元符号后跟名称表示 变量的。变量名区分大小写。

变量名称遵循与 PHP 中其他标签相同的规则。有效的 变量名以字母或下划线开头,后跟任何 字母、数字或下划线的数量。

我见过的边缘情况是紧接着美元符号之后的字符不是字母或下划线(或其他一些会调用特殊含义的元字符组合,例如第二个字符)的情况美元符号)。下面是一个示例:

$someVariable = "This is a $(test of our edge case).";

我可以使用 echo 语句输出此变量,并且单词 test 之前的美元符号毫无问题地显示(无需转义)。据我所知,PHP 没有抛出任何错误或警告。现在我的问题是:这是处理器语法中的边缘情况吗?这是一个错误吗?或者这是否有我忽略的其他解释?

我很清楚,作为一种良好的编程实践,当想要打印所述字符时,应该始终转义双引号字符串中的美元符号(或者可以简单地使用单引号字符串)。我只是好奇为什么这种情况不一定需要在美元符号之前转义。

I've run into what seems like a strange edge case with the PHP processor. According to the PHP manual:

Variables in PHP are represented by a dollar sign followed by the name
of the variable. The variable name is case-sensitive.

Variable names follow the same rules as other labels in PHP. A valid
variable name starts with a letter or underscore, followed by any
number of letters, numbers, or underscores.

The edge case I've seen is the case where the character immediately after the dollar sign is not a letter or underscore (or some other meta-character combination that would invoke a special meaning, such as a second dollar sign). Here's an example:

$someVariable = "This is a $(test of our edge case).";

I can output this variable with an echo statement, and the dollar sign before the word test shows up with no problem (no escape was necessary). PHP throws no error or warning, as far as I can tell. So now to my question: is this an edge-case in the processor grammar? Is it a bug? Or does this have some other interpretation that I'm overlooking?

I'm well aware that, as a good programming practice, one should always escape the dollar sign in a double-quoted string when one wants to print said character (or one could simply use a single-quoted string). I was just curious as to why this case didn't necessarily require an escape before the dollar sign.

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

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

发布评论

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

评论(1

冬天旳寂寞 2025-01-03 05:01:23

不,没有错误消息,没有错误。 PHP 只会扩展双引号括起来的字符串内的有效变量。

如果您熟悉正则表达式,您可以将其视为 PHP 将双引号字符串的内容与以下表达式进行匹配:

\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

No, there is no error with the lack of the error message. PHP will only expand valid variables inside of double quoted enclosed strings.

If you are familiar with regular expressions, you can think of it as PHP is matching the contents of double quoted strings with the following expression:

\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文