RE: [PHP] Class Constant PHP 5

From: Date: Wed, 07 Dec 2005 18:22:19 +0000
Subject: RE: [PHP] Class Constant PHP 5
Groups: php.general 
Request: Send a blank email to php-general+get-227076@lists.php.net to get a copy of this message
[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));

« previous php.general (#227076) next »