开发者

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. This solution works but my constant is now unnecessarily global.

Is there a way to define开发者_开发百科 a class constant at runtime in php?

Thank you.


See the PHP manual on Class constants

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.


Another option is to use the magic methods __get() and __set() to reject changes to certain variables. 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;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜