Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Testing isset($this) wasn't working for me, as mentioned by troelskn "$this will be set as the callers context."</p> <pre><code>abstract class parent { function bar() { if( isset( $this ) ) do_something(); else static::static_bar(); } function static static_bar() { do_something_in_static_context(); } } class child extends parent { ... } $foo = new child(); $foo-&gt;bar(); //results in do_something() child::bar(); //also results in do_something() </code></pre> <p>In my case, I have a parent class with a object and static context function that performs the same task within a child class. isset( $this ) was always returning true, however, I noticed that while $this switches between being class child in object context and calling(?) class on static context, the wonderful <code>__class__</code> magic constant, remained as class parent!</p> <p>Shortly there-after finding the function is_a, we can now test if we're in static context:</p> <pre><code>if( is_a($this, __CLASS__) ) ... </code></pre> <p>Returns true on object context, false on static context.</p> <p>Please test for your own implementations, as I'm only testing this for my specific scenario (a unique case of inheritance calling) in 5.3. </p> <p>Unfortunately (for my case) I am yet unable to find a way to call the <code>static_bar()</code> since $this and static are referring to a separate class, and <code>__class__</code> is referring to the parent class. What I need is a way to call child::static_bar()...</p>
 

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