12

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';
1
  • 5
    Welcome to SO. This has already been discussed in depth here: stackoverflow.com/questions/3960323/… the answer is long :) Anyway, it's definitely not possible, you may want to leave it at that. Commented Apr 2, 2011 at 22:44

2 Answers 2

25

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi, thanks. Ok that kind of makes sense then. Whats the best practice for doing this kind of thing as it must happen quite a lot - where a constant value is requried but it is defined from a function call or something.
2

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

5 Comments

Yes but i am not trying to change the value of a constant, instead i am trying to initialise it with the value of a function.
I understand what you mean. However, if the function could initialize a constant, theoretically it would be able to change its value. Because the constant must be initialized in the class (if it was declared in the class too).
"if the function could initialize a constant, theoretically it would be able to change its value". This doesnt make much sense to me. If a constant is initialized, its a constant. If its not initialized, it does not exists. There is never a change.
I'm sorry, I meant "if the function could (set) a constant value ..". Because the value of a constant must be set when declared and only once.
your answer is not helpful. This pattern is allowed in Java for final variables that are evaluated exactly once. Evidently it is not allowed in PHP. But the reason why has nothing to do with functions changing the value of a constant; there's no inherent reason why a variable could not be assigned once from the value of a function. If the programmer uses in this instance a function that does not return identical results for function calls with the same arguments... well, that's a poor choice on the part of the programmer to use for a definition of a constant. Otherwise, why not?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.