user2507818
user2507818

Reputation: 3037

php: issue with the output of var_dump($this)

<?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)

Upvotes: 1

Views: 1049

Answers (1)

Mark Baker
Mark Baker

Reputation: 212412

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

Upvotes: 1

Related Questions