|
Posted by Jay Blanchard on 12/07/05 20:22
[snip]
is there a way to dynamically define a class constant during runtime
in PHP 5?
for example I would like to achieve the result of something like:
class Example {
const FOO = bar();
}
However this would obviously give a parse error.
I know it is possible with variables but I would like it to be a
constant.
[/snip]
Well, first of all the syntax you describe above does not define a constant
at all, you would need to use define()
The second thing is good old basic OOP theory, you should declare a private
static variable
http://us3.php.net/private
http://us3.php.net/manual/en/language.oop5.static.php
Of course you could define a global constant and then pass it into your
object when instantiating it, but that is a bad idea generally.
Thirdly, you could never use a function to derive your constant value...it
would then be an oxymoron. If the value generated by the function bar()
changes, FOO is a variable. Constants are for simple values. For instance,
we can all agree that pi is 3.14159 (to 5 decimal places, so defining a
constant pi makes sense;
define("PI", 3.14159);
If we do not know what the outcome of a function will be it makes the value
of the outcome a variable, always. It would be foolish (and would fail
anyhow) to do something like this;
define("RANDOM", rand(5,12));
Navigation:
[Reply to this message]
|