Is there any way I can check if a method is being called statically or on an instantiated object?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
Testing isset($this) wasn't working for me, as mentioned by troelskn "$this will be set as the callers context."
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:
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()..."Digging it out of debug_backtrace()" isn't too much work. debug_backtrace() had a 'type' member that is '::' if a call is static, and '->' if it is not. So:
Check whether
$this
is definedThis is an old question, but I'll add an alternative answer.
There are two magic methods
__call($name, $arguments)
is triggered when invoking inaccessible methods in an object context.
__callStatic($name, $arguments)
is triggered when invoking inaccessible methods in a static context.
Outputs
Try the following:
Source: seancoates.com via Google
Test for
$this
:Edit: As pygorex1 points out, you can also force the method to be evaluated statically: