You assume that php runs from top to bottom, but this is not entirely true:
<?php foo(); # works function foo(){ print "bar"; }
<?php foo(); #dies if( $i == 1 ) { function foo(){ print "bar"; } }
<?php $i = 1; if( $i == 1 ) { function foo(){ print "bar"; } } foo();
Now, although you can conditionally create classes:
<?php class A { } class B { } if( false ){ class C extends B { public static function bar(){ print "baz"; } } } C::bar();
You cannot create an instance at runtime from a variable:
<?php class A { } class B { } $x = 'B'; if( false ){ class C extends $x { public static function bar(){ print "baz"; } } } C::bar(); ---> Parse error: syntax error, unexpected T_VARIABLE, expecting T_STRING in /tmp/eg.php on line 7
There is a way to do this with Eval, but you really don't want to go there:
<?php class A { } class B { } $x = 'B'; if( true ){ $code =<<<EOF class C extends $x { public static function bar(){ print "baz"; } } EOF; eval( $code ); } C::bar(); $o = new C; if ( $o instanceof $x ) { print "WIN!\n"; } --->barWIN!
However, there is a more important question here:
Why the hell do you want to extend the class at runtime
Anyone who uses your code will want to hold you back and knock you out for it.
(Alternatively, if you are in a beating, do this trick)