PHP 中是否可以将常量命名为受保护的字?
在 C# 中,变量和其他事物可以通过在名称前添加 @ 符号来命名为受保护的名称,例如“类”。所以,@class 是一个有效的名称。在 PHP 中可以做同样的事情吗?我使用一类常量来模拟 HTML 属性(例如 ID 和 Class)的枚举。现在我使用“CssClass”,但我宁愿以某种方式使用名称 Class。
In C#, variables and other things can be named protected names such as "class" by prepending the name with an @ sign. So, @class is a valid name. Is it possible to do this same thing in PHP? I am using a class of constants to simulate an enum for HTML attributes such as ID, and Class. For now I am using "CssClass" but I'd rather use the name Class somehow.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,不可能,至少对于类常量来说是不可能的。
我不了解 C#,但 PHP 中没有任何特殊符号可以将关键字转换为标识符。只要您不将其命名为与关键字完全相同(字母大小写除外),它就只是任何普通的常量名称。
一个(不同,因为它不仅仅是CSS)前缀怎么样?打字重复,但这是一个很好的解决方法。我意识到,如果您的类被命名为类似
HTMLAttribute
的名称,这也可能是多余的,但这是最简单的方法。Nope, not possible, at least not for class constants.
I don't know about C#, but there isn't any special symbol in PHP to transform a keyword into an identifier. As long as you don't name it exactly the same as a keyword (barring letter case), it'll just be any normal constant name.
How about a (different since it's not just CSS) prefix? Gets repetitive to type, but is a nice workaround. I realize this may be redundant as well if your class is named something like
HTMLAttribute
, but it's the easiest way out.是的,这是可能的。
事实上,您可以将任何内容定义为常量:
但是,您不能不使用所有已定义的常量。
您可以再次使用
constant("if")
查询它们。但这并不完全是您所要求的。因此,与 C# 不同,没有使用任何随机常量的快捷方式。但至于命名,几乎没有任何限制。 (不过可能是一个错误。它是 PHP。)Yes, it is possible.
In fact you can define anything as constant:
However, you can not use all defined constants.
You can query them with
constant("if")
again. But this is not exactly what you asked for. So unlike C# there is no shortcut to use any random constant. But as for naming them, there are almost no restrictions. (Might be a bug though. It's PHP.)常量:
保留关键字列表:
在这些规则中,您可以自由地命名您的名字。例如,您可以命名一个常量
_CLASS
,但不能命名为CLASS
。我会避免使用此类不明确的名称和应用程序特有的命名空间常量,例如 MYAPP_CLASS 。Constants:
List of reserved keywords:
Within these rules you're free to make up your names. So, for instance, you could name a constant
_CLASS
, but notCLASS
. I'd avoid the use of such ambiguous names though and namespace constants that are particular to the app, likeMYAPP_CLASS
.从 PHP5 到 PHP7,类常量几乎可以命名为任何名称:
但是,多亏了 this手册的一部分和此评论,我发现类常量不能被命名为以下几件事(请参阅测试此处):
class
static
__halt_compiler
(哦,这太有用了!)编辑:正如我在 在 RFC 中,
class
常量不起作用的原因是名称解析<代码>::类。然而,对于另外两个人,仍然一无所知。Going from PHP5 to PHP7, a class constant could be named almost anything:
However, thanks to this part of the manual and this comment, I've found that a class constant cannot be named these few things (see the test here):
class
static
__halt_compiler
(oh, that was so useful!)Edit: As I found in here in an RFC, the reason why
class
constant does not work is the name resolution::class
. However, still no idea about the two others.