SiC_Goat Posted October 20, 2008 Share Posted October 20, 2008 Is there a way, without instantiating an object, to access a static property of a class based solely on a string? Class MyClass { public static $MyProperty = 'MyValue'; } $className = 'MyClass'; $classProp = /* magic */; In need of 'magic' Quote Link to comment Share on other sites More sharing options...
rhodesa Posted October 20, 2008 Share Posted October 20, 2008 the only way i can think of uses eval: <?php Class MyClass { public static $MyProperty = 'MyValue'; } $className = 'MyClass'; print eval('$classProp = '.$className.'::$MyProperty;'); print $classProp; ?> you could write a static function to return the value: <?php Class MyClass { public static $MyProperty = 'MyValue'; public static function getProp ( ) { return self::$MyProperty; } } $className = 'MyClass'; $classProp = call_user_func(array($className,'getProp')); print $classProp; ?> Quote Link to comment Share on other sites More sharing options...
SiC_Goat Posted October 20, 2008 Author Share Posted October 20, 2008 Interesting idea, didn't know you could use call_user_func on static portions of an object that way. I'll probably just write a static property method that takes in a $name and return self::$name or something. Better than any non-solution I have so far. Quote Link to comment Share on other sites More sharing options...
ignace Posted October 20, 2008 Share Posted October 20, 2008 otherwise take a look at PEAR.php which "emulates" static properties, their solution to cover the php4 disability on static properties, don't know if this is what you were looking for Quote Link to comment Share on other sites More sharing options...
discomatt Posted October 20, 2008 Share Posted October 20, 2008 As of 5.3.0 you should be able to use $className::$MyProperty Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.