Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You're assuming here php executes top to bottom, but it doesn't quite work like that: </p> <pre><code>&lt;?php foo(); # works function foo(){ print "bar"; } </code></pre> <hr> <pre><code>&lt;?php foo(); #dies if( $i == 1 ) { function foo(){ print "bar"; } } </code></pre> <hr> <pre><code>&lt;?php $i = 1; if( $i == 1 ) { function foo(){ print "bar"; } } foo(); #works </code></pre> <hr> <p>Now, although you can conditionally create classes: </p> <pre><code>&lt;?php class A { } class B { } if( false ){ class C extends B { public static function bar(){ print "baz"; } } } C::bar(); # dies </code></pre> <p>You cant instantiate one at runtime from a variable: </p> <pre><code>&lt;?php class A { } class B { } $x = 'B'; if( false ){ class C extends $x { public static function bar(){ print "baz"; } } } C::bar(); ---&gt; Parse error: syntax error, unexpected T_VARIABLE, expecting T_STRING in /tmp/eg.php on line 7 </code></pre> <p>There is a way to do it with Eval, but you <em>really</em> don't want to go there: </p> <pre><code>&lt;?php class A { } class B { } $x = 'B'; if( true ){ $code =&lt;&lt;&lt;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"; } ---&gt;barWIN! </code></pre> <p>However, there is a more important question here: </p> <p><strong>Why the hell would you <em>want</em> to extend a different class at runtime </strong> </p> <p>Anybody using your code will want to hold you down and <em>whip</em> you for that.</p> <p>( Alternatively, if you're into whipping, do that eval trick )</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload