Can PHP Perform Magic Instantiation?
<p>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....</p>

<p>... I will admit, it is quite fun to program in and is fairly ubiquitous. (<em>waiting for Server-side JavaScript to flesh out though</em>)</p>

<p><strong>question</strong>:
Given a class <code>class RandomName extends CommonAppBase {}</code> is there any way to automatically create an instance of any class extending <code>CommonAppBase</code> without explicitly using <code>new</code>?</p>

<p>As a rule there will only be one class definition per PHP file. And appending <code>new RandomName()</code> to the end of all files is something I would like to eliminate. The extending class has no constructor; only <code>CommonAppBase</code>'s constructor is called. <code>CommonAppBase-&gt;__construct()</code> kickstarts the rest of the apps execution.</p>

<p>Strange question, but would be nice if anyone knows a solution.</p>

<h2>Edit</h2>

<p>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 <code>include('random.class.php')</code> and instantiate whatever class extending <code>CommonAppBase</code> is in there.</p>

<p>For anyone unsure what I am after <a href="http://stackoverflow.com/questions/2813413/can-php-perform-magic-instantiation/2813734#2813734">my hackish answer</a> does what I want, but not in the sanest way.</p>

<p>Thanks in advance,
Aiden</p>

<p>(btw, my PHP version is 5.3.2) Please state version restrictions with any answer.</p>

<h2>Answers</h2>

<p>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.</p>

<p>First (thanks dnagirl)</p>

<pre><code>$ca = get_declared_classes();
foreach($ca as $c){
    if(is_subclass_of($c, 'MyBaseClass')){
        $inst = new $c();
    }
}
</code></pre>

<p>and (the accepted answer, as closest answer)</p>

<pre><code>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];
    }
}
</code></pre>
