[英]Defining class constant in PHP
I would like to define a class constant using a concatenation of an existing constant and a string. 我想使用现有常量和字符串的串联来定义类常量。 I can't predefine it because only scalars are allowed for predefining constants, so I currently have it as part of my constructor with a defined() function checking if it is already defined.
我无法预定义它,因为只允许使用标量来预定义常量,所以我现在将它作为构造函数的一部分,并使用defined()函数检查它是否已经定义。 This solution works but my constant is now unnecessarily global.
这个解决方案有效,但我的常数现在已经不必要了。
Is there a way to define a class constant at runtime in php? 有没有办法在运行时在PHP中定义类常量?
Thank you. 谢谢。
See the PHP manual on Class constants 请参阅类常量的PHP手册
The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call.
该值必须是常量表达式,而不是(例如)变量,属性,数学运算的结果或函数调用。
In other words, it is not possible. 换句话说,这是不可能的。 You could do it with runkit_constant_add but this sort of monkey patching is strongly discouraged.
你可以用runkit_constant_add做到这一点,但强烈建议不要使用这种猴子补丁。
Another option is to use the magic methods __get() and __set() to reject changes to certain variables. 另一种选择是使用魔术方法__get()和__set()来拒绝对某些变量的更改。 This is not so much a constant as a read-only variable (from the perspective of other classes).
这不是一个只读变量的常量(从其他类的角度来看)。 Something like this:
像这样的东西:
// Completely untested, just an idea
// inspired in part from the Zend_Config class in Zend Framework
class Foobar {
private $myconstant;
public function __construct($val) {
$this->myconstant = $val;
}
public function __get($name) {
// this will expose any private variables
// you may want to only allow certain ones to be exposed
return $this->$name;
}
public function __set($name) {
throw new Excpetion("Can't set read-only property");
}
}
You cannot do exactly what you want to do, per Gordon's answer . 根据戈登的回答 ,你不能做你想做的事。 However, you can do something like this.
但是,你可以做这样的事情。 You can only set it once:
您只能设置一次:
class MyClass
{
private static $myFakeConst;
public getMyFakeConst()
{
return self::$myFakeConst;
}
public setMyFakeConst($val)
{
if (!is_null(self::$myFakeConst))
throw new Exception('Cannot change the value of myFakeConst.');
self::$myFakeConst = $val;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.