class RandomName extends CommonAppBase {}Is there a way for a class to automatically instantiate any class that extends CommonAppBasewithout explicit use new?
Typically, there will be only one class definition for each PHP file. And adding new RandomName()to the end of all the files is what I would like to eliminate. An expanding class does not have a constructor; only the constructor is CommonAppBasecalled. CommonAppBase->__construct()launches the rest of the application execution.
Strange question, but it would be nice if someone knew the solution.
Edit
In addition to the following comment. The code that creates the instance will not be in the class file. The class file will be just that, I want some other code to be include('random.class.php')and create an instance of any class extension CommonAppBase.
For anyone who is not sure that after my hacker answer , I do what I want, but not in the safest way.
Thanks in advance, Aiden
(btw, my version of PHP is 5.3.2). Please indicate version restrictions with any answer.
The answers
The following can be added to the file (via php.ini or with Apache): automatically run the class of the specific parent class.
At first (thanks dnagirl)
$ca = get_declared_classes();
foreach($ca as $c){
if(is_subclass_of($c, 'MyBaseClass')){
$inst = new $c();
}
}
and (accepted answer as closest answer)
auto_loader();
function auto_loader() {
$classes = array_filter(get_declared_classes(), function($class){
return get_parent_class($class) === 'MyBaseClass';
});
if (isset($classes[0])) {
$inst = new $classes[0];
}
}
source
share