使用特殊字符的 PHP 变量/函数/类名

2022-01-25 00:00:00 function label syntax php

我知道下划线 _ 是用于命名变量/函数/类等的可接受字符.但是我想知道是否还有其他可以使用的特殊字符.我测试了一些没有运气的东西,并且长期以来一直认为没有,但是我想我会看看是否有其他人肯定知道.这主要是出于审美目的,但我认为特殊字符命名约定在与其他开发人员合作定义值类型等时会很有用.

I understand that the underscore _ is an acceptable character for naming variables / functions / classes etc. However I was wondering if there are any other special characters which can be used. I tested out a few with no luck and have assumed for a long time that there are not, however I figured I would see if anyone else knows for certain. This would be mostly for aesthetic purposes, however I imagine a special character naming convention would be useful when working with other developers to define value types etc.

推荐答案

如果你检查 docs on variables 它说:

If you check the docs on variables it says that:

变量名称遵循与 PHP 中其他标签相同的规则.有效的变量名称以字母或下划线开头,后跟任意数量的字母、数字或下划线.作为一个正则表达式,它会这样表达:'[a-zA-Z_x7f-xff][a-zA-Z0-9_x7f-xff]*'

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. As a regular expression, it would be expressed thus: '[a-zA-Z_x7f-xff][a-zA-Z0-9_x7f-xff]*'

但基本上人们已经同意只使用 a-zA-Z0-9_ 而不是花哨"的名称,因为它们可能会因使用的编码而中断.

But basically people have agreed to only use a-zA-Z0-9_ and not the "fancy" names since they might break depending in the encoding one uses.

所以你可以有一个名为$aöäüÖÄ的变量,但如果你用错误的编码保存它,你可能会遇到麻烦.

顺便说一句,函数也是如此.

The same goes for functions too btw.

所以

function fooööö($aà) { echo $aà; }

fooööö("hi"); // will just echo 'hi'

会解决的(至少一开始是这样).

will just work out (at least at first).

也可以看看:

Exotic方法、常量、变量和字段的名称 - Bug 还是 Feature?

关于这个主题的一些讨论.

for some discussion on the subject.

相关文章