Re: Class Constant PHP 5

From: Date: Thu, 08 Dec 2005 02:13:28 +0000
Subject: Re: Class Constant PHP 5
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-227099@lists.php.net to get a copy of this message
The point was more that the constant's value is 'defined' at the beginning of the script, and is constant and non changing throughout the entire execution of the script. But I was looking for a way to give it a namespace inside a class rather than just defining in in the global scope so that I do not have to worry about conflicting names with other packages such as PEAR et al. I wanted to do something like: <? define('ClassName::ConstantName',$valueDeterminedAtStartOfScript); ?> so that I I could later use the notation $value = ClassName::ConstantName or from within the class $value = self::ConstantName and ensure other developers could not change the value of the constant. To achieve the result I want I could do: <? define ('foo',$valueDeterminedAtStartOfScript); class ClassName { const ConstantName = foo; } ?> But that just seems pointless and messy. I will assume that the simple answer to my original question was 'No that it is not possible'. Thanks - Jeff Jeffrey Sambells cell 519.897.2552 phone 905.878.4701 web http://www.sambells.info On 7-Dec-05, at 1:22 PM, Jay Blanchard wrote:
[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 (#227099) next »