可以在 PHP 的类中使用静态常量吗?
我预计以下内容会起作用,但似乎没有。
<?php
class Patterns
{
public static const EMAIL = "/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix";
public static const INT = "/^\d+$/";
public static const USERNAME = "/^\w+$/";
}
因为它会抛出这个错误:
syntax error, unexpected T_CONST, expecting T_VARIABLE
I expected the following to work but it doesn't seem to.
<?php
class Patterns
{
public static const EMAIL = "/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix";
public static const INT = "/^\d+$/";
public static const USERNAME = "/^\w+$/";
}
Because it throws this error:
syntax error, unexpected T_CONST, expecting T_VARIABLE
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您如何尝试访问常量?
我相信这会起作用:
如果你只是将其声明为静态。
How are you trying to access the constants?
I believe this would work:
If you just declare it as static.
不,类常量不能标记为静态,也不能指定可见性。
http://php.net/manual/en/language.oop5.static.php
Nope class constants can't be labeled static nor assigned visibility.
http://php.net/manual/en/language.oop5.static.php
您不需要将它们声明为静态或公共。查看手册中的示例:
http://www.php。 net/manual/en/language.oop5.constants.php
You don't need to declare them static or public. Check out the examples in the manual:
http://www.php.net/manual/en/language.oop5.constants.php
您可以在类中使用 const,如下所示:
并且可以像这样访问
USERNAME
const:You can use const in class like this:
And can access
USERNAME
const like this:在 PHP 中,static 和 const 是两个不同的东西。
const 表示类常量。它们与普通变量不同,因为它们前面没有“$”,并且前面不能有任何可见性修饰符(public、protected、private)。它们的语法:
因为它们是恒定的,所以它们是不可变的。
静态表示同一类的对象之间共享的数据。该数据可以修改。一个例子是一个类,它跟踪任意时刻有多少个实例正在运行:
In PHP, static and const are two different things.
const denotes a class constant. They're different than normal variables as they don't have the '$' in front of them, and can't have any visibility modifiers (public, protected, private) before them. Their syntax:
Because they're constant, they're immutable.
Static denotes data that is shared between objects of the same class. This data can be modified. An example would be a class that keeps track of how many instances are in play at any one time:
它们不是静态常量,只是常量
They're not static constants, just constants