Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How can $this variable inside one class be object of another one?

Here is an example:

class Test {

    public function TestMethod() {

        print_r($this); // Gives me "Test1 Object ( )"

    }
}

class Test1 {

    public function Test1Method() {

        Test::TestMethod();

    }
}

$test1 = new Test1;
$test1->Test1Method();

I find this strange. Can anyone please explain to me why it happens?

like image 564
foreline Avatar asked Jan 21 '11 15:01

foreline


2 Answers

From http://www.php.net/manual/en/language.oop5.basic.php:

The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).

This doesn't necessarily make a lot of sense, though, and will invoke a warning if E_STRICT is enabled.

like image 68
Oliver Charlesworth Avatar answered Oct 15 '22 07:10

Oliver Charlesworth


Short answer: You are calling a "non static" method using a static function call, php then tries to find a "$this" and the last real "$this" was the one in Test1.

If you turn on E_STRICT error reporting it will complain about that.

like image 42
edorian Avatar answered Oct 15 '22 07:10

edorian