Setting class constants after constructor?

I have a class with the following diagram

class MyClass { const x = 'abc'; const y = '123'; function _contruct() {} } 

Is there any way for me to keep the constants unset in the body of the class and dynamically set after calling the constructor? For example, something like this:

 class MyClass { const x; const y; function _contruct() { $this->setStuff(); } function setStuff() { $this->x = Config::getX(); $this->y = Config::getY(); } } 
+6
oop php class
source share
5 answers

As the name implies, this value cannot change during script execution (except for the magic of constants, which are not actually constants) ( http://php.net/manual/en/language.constants.php )

So no. You can make them private vars.

+6
source share

Not. Class constants (and global namespace constants defined using the const keyword) must be literal values ​​and must be set before runtime. This is where they differ from the old school constants define() that are set at runtime. It is not possible to change or set the const during script execution.

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

from the PHP manual: Class Constants

So maybe:

 define('MY_CONST', someFunctionThatReturnsAValue()); 

But this is not so:

 const MY_CONST = someFunctionThatReturnsAValue(); // or class MyClass { const MY_CONST = = someFunctionThatReturnsAValue(); } // or namespace MyNamespace; const MY_CONST = someFunctionThatReturnsAValue(); 

And using $this in your example, you can assume that you are trying to set constants at the instance level, but class constants are always statically defined at the class level.

+4
source share

No, constants are constants because they must be constant. First declaring them empty and changing these values ​​with something else means that they are variables. Since your goal is to set them once, but not after, consider the Injection construct, for example

 class MyClass { private $x; private $y; public function __construct($x, $y) { $this->x = $x; $this->y = $y; } } 

As long as your class does not provide any methods to modify $x and $y , and you do not produce them internally, they are effectively constant. The only thing you cannot do with non-public variables is then MyClass::X , but I believe that you should not use class constants outside their respective classes, since it introduces a relationship between the consumer and the class.

Just like that.

+3
source share

Constants "constant" . You cannot change it.

You can use a variable for this.

+1
source share

impossible. If you can set x and y in setStuff (), you can also (re) set them in any other way. By definition, a constant cannot change. Therefore, your x and y will be variables, not constants.

+1
source share

All Articles