Despite PHP being a pretty poor language and ad-hoc set of libraries ... of which the mix of functions and objects, random argument orders and generally ill-thought out semantics mean constant WTF moments....
... I will admit, it is quite fun to program in and is fairly ubiquitous. (waiting for Server-side JavaScript to flesh out though)
question:
Given a class class RandomName extends CommonAppBase {}
is there any way to automatically create an instance of any class extending CommonAppBase
without explicitly using new
?
As a rule there will only be one class definition per PHP file. And appending new RandomName()
to the end of all files is something I would like to eliminate. The extending class has no constructor; only CommonAppBase
's constructor is called. CommonAppBase->__construct()
kickstarts the rest of the apps execution.
Strange question, but would be nice if anyone knows a solution.
Edit
Further to the below comment. The code that does the instantiation won't be in the class file. The class file will be just that, I want some other code to include('random.class.php')
and instantiate whatever class extending CommonAppBase
is in there.
For anyone unsure what I am after my hackish answer does what I want, but not in the sanest way.
Thanks in advance, Aiden
(btw, my PHP version is 5.3.2) Please state version restrictions with any answer.
Answers
The following can all be appended to a file (through php.ini or with Apache) to auto launch a class of a specific parent class.
First (thanks dnagirl)
$ca = get_declared_classes();
foreach($ca as $c){
if(is_subclass_of($c, 'MyBaseClass')){
$inst = new $c();
}
}
and (the accepted answer, as closest answer)
auto_loader();
function auto_loader() {
// Get classes with parent MyBaseClass
$classes = array_filter(get_declared_classes(), function($class){
return get_parent_class($class) === 'MyBaseClass';
});
// Instantiate the first one
if (isset($classes[0])) {
$inst = new $classes[0];
}
}