Tech Lull
 
 
JavaPHPSQLDrupalOpenGLMathematicsRenderings
 
 

'Dynamic' Calling of Static Classes

back to PHP tips...
Printer friendlyPrinter friendly

Suppose you want to dynamically call a static function because you don't know ahead of time which one you will need. For instance, you might have two subclasses of a base class. If they were normal classes you could easily do this using a variable string an instance creation or polymorphism.

$instance = new $which_class();

The same does not hold true for static classes. However, on the zend.com forums page, I got this solution which uses the eval() function. Now, I normally do not use the eval() function because it has some security risks, etc. But, it is very useful in this case. FYI, I came across this problem when trying to dynamically select a registry class which was based on a singleton pattern.

class A { public static function instance(){ } } class B { public static function instance(){ } } $obj_type = 'A'; $instance = eval("return {$obj_type}::instance();");

One final note is that you must include return in the function argument if you wish to return a value, and not just evaluate a statement.

Your rating: None Average: 4 (1 vote)
back to PHP tips...