Calling a method once all the script processing has completed
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.
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).
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.
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.
Here's an example of the code I had so far:
class Application {
static $_instance = null;
public static function getInstance(){
if ( $this->_instance == null ){
$this->_instance = new get_called_class();
}
return $this->_instance;
}
}
function findApplicationClass(){
$classes = get_declared_classes();
foreach ( $classes as $class ){
$c = new ReflectionClass ($class);
if ( $c->isSubclassOf("Application")
&& $c->hasMethod("Main") ){
call_user_func($class . '::Main');
}
}
}
function runApplication(){
findApplicationClass();
}
register_shutdown_function('runApplication');
And then your application is simply:
include "../lib/com/crt0/crt0.p开发者_开发问答hp";
class MyApplication extends Application {
static public function Main ( ){
echo "Main function";
}
}
You should use classes autoloading feauture instead of your include() to load them to avoid dirty tricks ;)
精彩评论