class Config { const TEST = "This is a Constant"; static public $test = "This is a static property test." static protected $test2; public static function initialize() { self::$test2 = 'initialized'; return self::$test2; } public static function getTest2() { return self::$test2; } } echo Config::TEST;
If you need to dynamically set a value, you do not want to use the constant that you want to use the static property. IF you want the Config class to be able to directly manipulate the value of this property, use the private or protected keyword. If this is not a problem, you can use the public property.
Another and possibly the most reliable approach, depending on what you are trying to implement, is to use constants to access static or instance-specific class properties:
class Config { const TEST = 0; const TEST2 = 1; protected static $conf = array(); public static function initialize($testVal, $test2Val) { $conf[self::TEST] = $testVal; $conf[self::TEST2] = $test2Val; } public static function get($key) { if(isset(self::$conf[$key]) { return self::$conf[$key]; } } } Config::initialize('Test', 'Test 2'); echo Config::get(Config::TEST); echo Config::get(Config::TEST2);
prodigitalson Apr 19 '11 at 1:45 a.m. 2011-04-19 01:45
source share