Is there any way I can check if a method is being called statically or on an instantiated object?
Testing isset($this) wasn't working for me, as mentioned by troelskn "$this will be set as the callers context."
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->bar(); //results in do_something()
child::bar(); //also results in do_something()
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 __class__ magic constant, remained as class parent!
Shortly there-after finding the function is_a, we can now test if we're in static context:
if( is_a($this, __CLASS__) ) ...
Returns true on object context, false on static context.
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.
Unfortunately (for my case) I am yet unable to find a way to call the static_bar() since $this and static are referring to a separate class, and __class__ is referring to the parent class. What I need is a way to call child::static_bar()...