Calling a method once all the script processing has completed
<p>I'm trying to do a bit of "fancy"/"experimental" php so that you can include a header script (called crt0 :-p) that defines a basic application class that you can inherit.</p>

<p>It then provides a function that checks your classes and finds one that is subclassing it's application class and calls the "Main" function. This way you include the header, create a class that subclasses the default application class and ensure you provide a static main function and voila - you application magically picks up inside the main function (similar to java/c#, etc with lots of pre-defined application functionality).</p>

<p>The only issue I'm having is "waiting" until the users application class is defined; Because the include that defines the application class has to come before your user implementation the "check" is also being called within the same script and before the user defines their function so isn't finding the users class as it hasn't yet been defined.</p>

<p>The "trick" i was using was cuasing the application to run inside the register_shutdown_function function to then find the class and run it; It works fine as by this point all the classes have been defined but I'm not sure what state the system/script/process is in during this shutdown process and whether it's safe to start running code here :-p.</p>

<p>Here's an example of the code I had so far:</p>

<pre><code>class Application {

    static $_instance = null;

    public static function getInstance(){
        if ( $this-&gt;_instance == null ){
            $this-&gt;_instance = new get_called_class();
        }
        return $this-&gt;_instance;
    }

}

function findApplicationClass(){
    $classes = get_declared_classes();
    foreach ( $classes as $class ){
        $c = new ReflectionClass ($class);
        if ( $c-&gt;isSubclassOf("Application")
        &amp;&amp;    $c-&gt;hasMethod("Main") ){
            call_user_func($class . '::Main');
        }
    }
}

function runApplication(){
    findApplicationClass();
}

register_shutdown_function('runApplication');
</code></pre>

<p>And then your application is simply:</p>

<pre><code>include "../lib/com/crt0/crt0.php";

class MyApplication extends Application {

    static public function Main ( ){
        echo "Main function";
    }
}
</code></pre>
