'Why is the usage of $this in PHP necessary when referencing methods or variables in the same class?

I was explaining to a Java developer why his method call wasn't working. He just needed to add $this->method_name();

He then asked me, "Why do I need to add $this to the method when it's declared in the same class?"

I didn't really know how to answer. Maybe it's because PHP has a global namespace and it you need to explicitly tell it that the method you are looking for belongs to the current class? But then why doesn't PHP check the current class for the method BEFORE looking at the global namespace?



Solution 1:[1]

If I have to guess: Because it was easier than the alternatives. Object oriented support in PHP has always been very much of a hack. I vaguely remember reading a discussion about the upcoming closure support that will appear in PHP 5.3. Appearently it was really, really hard to implement lexical closures in PHP due to it's scoping rules. Probably because you can nest a class in a function in another class and stuff like that. All that freedom possibly makes stuff like this incredibly hard.

Solution 2:[2]

This is not unusual. Python, Javascript, Perl (and others) all make you refer to a this or self when dealing with objects.

Solution 3:[3]

That's just how scope works in PHP. $obj->f() refers to $foo in the function scope. If you want to get the class property $obj->foo within f(), it's $this->foo.

global $foo;
$foo = 99;

class myclass
{
    public $foo;

    function f()
    {
        $this->foo = 12;
        $foo = 7;

        // $this->foo != $foo != $GLOBALS['foo']
    }
}

Solution 4:[4]

$this refers to the calling object. The PHP docs have good examples and further details.

Solution 5:[5]

Seems PHP hasn't been properly OOPed. In Java and C++, references to the current object ('this') are implicit, ie no explicit mention is needed, leaving the code much cleaner. Perhaps there is some reason this is difficult with PHP implementation ?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Emil H
Solution 2 gnud
Solution 3 Annika Backstrom
Solution 4 canen
Solution 5