10

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';
Usama Abdulrehman
  • 1,041
  • 3
  • 11
  • 21
David
  • 103
  • 1
  • 4
  • 4
    Welcome to SO. This has already been discussed in depth here: http://stackoverflow.com/questions/3960323/why-dont-php-attributes-allow-functions the answer is long :) Anyway, it's definitely not possible, you may want to leave it at that. – Pekka Apr 02 '11 at 22:44

2 Answers2

24

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.

KingCrunch
  • 128,817
  • 21
  • 151
  • 173
  • 1
    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. – David Apr 02 '11 at 22:48
2

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

Nabeel
  • 557
  • 4
  • 15
  • 1
    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. – David Apr 02 '11 at 22:52
  • 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). – Nabeel Apr 02 '11 at 22:57
  • "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. – KingCrunch Apr 02 '11 at 23:11
  • 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. – Nabeel Apr 02 '11 at 23:30
  • 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? – Jason S Apr 03 '11 at 03:19