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' Link to comment https://forums.phpfreaks.com/topic/129232-retrieve-static-properties-dynamically/ 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; ?> Link to comment https://forums.phpfreaks.com/topic/129232-retrieve-static-properties-dynamically/#findComment-670004 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. Link to comment https://forums.phpfreaks.com/topic/129232-retrieve-static-properties-dynamically/#findComment-670169 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 Link to comment https://forums.phpfreaks.com/topic/129232-retrieve-static-properties-dynamically/#findComment-670171 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 Link to comment https://forums.phpfreaks.com/topic/129232-retrieve-static-properties-dynamically/#findComment-670411 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.