Defining a class constant in PHP

I would like to define a class constant using the concatenation of an existing constant and string. I cannot predefine it, because only scalars are allowed to predefine constants, so at the moment I have it as part of my constructor with a specific function (), if it is already defined. This solution works, but my constant is now overly global.

Is there a way to determine the class constant at runtime in php?

Thanks.

+7
php constants
source share
3 answers

See the PHP manual for class constants

The value should be a constant expression, and not (for example) a variable, property, result of a mathematical operation, or a function call.

In other words, this is not possible. You can do this with runkit_constant_add , but this kind of monkey fix is ​​highly discouraged.

+9
source share

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 point of view of other classes). Something like that:

// 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"); } } 
+3
source share

You cannot do exactly what you want for Gordon's answer . However, you can do something similar. You can install it only 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; } } 
+3
source share

All Articles