PHP - assign function value to class constant

Well, this is a stupid question, but I can’t think about why he was stupid.

In php, when you define a class level constant, like in:

const MY_CONSTANT = 'hello constant';

why can't you initialize this value with a function like

const MY_FILEPATH = dirname(dirname(__FILE__)) . '/heres-my-file.php';
+5
source share
2 answers

In short: constants are replaced during parsing, but functions are executed during interpretation. The parser simply cannot know why it should set the content value.

+14
source

Constants are immutable. Therefore, if functions can change the value of a constant, this will not be a constant.

+1
source

All Articles