David
David

Reputation: 123

PHP - assign value of function to class constant

In PHP when you define a class level constant as in:

const MY_CONSTANT = 'hello constant';

Why can't you initialize this value with a function such as

const MY_FILEPATH = dirname(dirname(__FILE__)) . '/heres-my-file.php';

Upvotes: 12

Views: 7033

Answers (2)

Nabeel
Nabeel

Reputation: 557

Constants are immutable. Therefore, if functions could change the value of a constant it wouldn't be a constant.

Upvotes: 2

KingCrunch
KingCrunch

Reputation: 131841

In short: The constants are replaced while parsing, but functions are executed while interpreting. The parser simply cannot know to what it should set the value of the content.

Upvotes: 25

Related Questions