你可以在 PHP 中使用静态常量吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3389380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can you use static constants in PHP?
提问by Emanuil Rusev
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+$/";
}
I get syntax error, unexpected T_CONST, expecting T_VARIABLE
我得到 syntax error, unexpected T_CONST, expecting T_VARIABLE
回答by Naveed
You can use const in class like this:
您可以在类中使用 const ,如下所示:
class Patterns {
const EMAIL = "/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix";
const INT = "/^\d+$/";
const USERNAME = "/^\w+$/";
}
And can access USERNAMEconst like this:
并且可以USERNAME像这样访问const:
Patterns::USERNAME
回答by Major Productions
In PHP, static and const are two different things.
在 PHP 中,static 和 const 是两种不同的东西。
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:
const 表示类常量。它们与普通变量不同,因为它们前面没有“$”,并且前面不能有任何可见性修饰符(public、protected、private)。他们的语法:
class Test
{
const INT = "/^\d+$/";
}
Because they're constant, they're immutable.
因为它们是恒定的,所以它们是不可变的。
Static denotes data that is shared between objects of the same class. This data canbe modified. An example would be a class that keeps track of how many instances are in play at any one time:
静态表示在同一类的对象之间共享的数据。这个数据可被修改。一个例子是一个类,它跟踪任何时候有多少实例在运行:
class HowMany
{
private static $count = 0;
public function __construct()
{
self::$count++;
}
public function getCount()
{
return self::$count;
}
public function __destruct()
{
self::$count--;
}
}
$obj1 = new HowMany();
$obj2 = new HowMany();
echo $obj1->getCount();
unset($obj2);
echo $obj1->getCount();
回答by Mark Baker
They're not static constants, just constants
它们不是静态常量,只是常量
class Patterns
{
const EMAIL = "/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix";
const INT = "/^\d+$/";
const USERNAME = "/^\w+$/";
}
echo Patterns::EMAIL;
回答by Sarfraz
Nope class constants can't be labeled static nor assigned visibility.
Nope 类常量不能被标记为静态,也不能被分配可见性。
回答by Scott Saunders
You don't need to declare them static or public. Check out the examples in the manual:
您不需要将它们声明为 static 或 public。查看手册中的示例:
回答by Chris
How are you trying to access the constants?
您如何尝试访问常量?
I believe this would work:
我相信这会奏效:
echo Patterns::$EMAIL; //shows "/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-...."
If you just declare it as static.
如果您只是将其声明为静态。

