简体   繁体   中英

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM