1
<?php class A { var $name= 'A'; function main($objC){ var_dump($this);B::request('init', $objC); } } class B { var $name= 'B'; function request($func, $objC){ if (method_exists($objC, $func)){ var_dump($this);$objC->$func($this); } } } class C { var $name= 'C'; function init($pobj){ var_dump($this); } } $objA = new A; $objB = new B; $objC = new C; $objA->main($objC); 

Output:

object(A)[1] public 'name' => string 'A' (length=1) object(A)[1] public 'name' => string 'A' (length=1) object(C)[3] public 'name' => string 'C' (length=1) 

I thought $this in Class B always means the object of that Class B. But seems not, can anyone explain: why var_dump($this); in class B, outputs below result not object(B)?

object(A)[1] public 'name' => string 'A' (length=1) 
2
  • B::request is a static call, not a call to any instance of B, so the var_dump($this) from B has no contect of B being $this Commented Aug 21, 2013 at 9:33
  • @MarkBaker oops removed my comment about static, thought the question was why $this is defined. Commented Aug 21, 2013 at 9:49

1 Answer 1

1

If you run this with full error logging enabled, it will explain why:

Strict Standards: Non-static method B::request() should not be called statically, assuming $this from incompatible context in /php/tests/o2.php on line 6

So basically, use of $this in a statically-called method is meaningless, so PHP actually tries to apply a context.... and looks like it applies $this from the calling method

Sign up to request clarification or add additional context in comments.

4 Comments

"$this in a statically-called method is meaningless" not always. The error is about incompatible context. If the context is the same, no error will be triggered afaik.
True: if the context is the same (i.e. I have method request in class A that references $this, and I call it statically from another method in A) then I don't get such a warning because the context isn't incompatible
I think my point is still valid though: because the context isn't compatible (ie there isn't an instance of B within the call hierarchy that can be referenced) then it's falling back to the previous (incompatible) context. Whatever the case, I wouldn't recommend it as good coding practise.
Thanks. it is helpful. BTW, how to run this with full error logging enabled?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.