Why is using $ this in PHP necessary when referring to methods or variables in the same class?

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

Then he asked me, "Why do I need to add $ this to a method when it is declared in the same class?"

I really didn't know how to answer. Maybe because PHP has a global namespace and you need to explicitly say 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?

+1


a source to share


5 answers


The problem is also that if you declared a function foo()

method foo()

, php would have a hard time figuring out what you meant - consider this example:

<?php
function foo()
{
    echo 'blah';
}

class bar
{
    function foo()
    {
         echo 'bleh';
    }
    function bar()
    {
         // Here, foo() would be ambigious if $this-> wasn't needed.
    }
}
?>

      



So basically you can say that PHP - because of its "non-100% object-orientedness" (which means you can also have functions outside of classes) - has this "function" :)

+8


a source


If I have to guess: because it was easier than the alternatives. Object oriented support in PHP has always been very difficult. I vaguely remember reading the discussion about the upcoming closure support coming in PHP 5.3. Apparently it was really very difficult to implement lexical closures in PHP due to its scoping rules. Probably because you can nest a class within a function in another class and so on. All this freedom makes things like this incredibly difficult.



+4


a source


This is not uncommon. Python, Javascript, Perl (and others) allow you to reference this

or self

work with objects.

+3


a source


How scoping works in PHP. $obj->f()

refers to $foo

in the area of ​​functions. If you want to get a property of a class $obj->foo

inside f()

, it is $this->foo

.

global $foo;
$foo = 99;

class myclass
{
    public $foo;

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

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

      

+1


a source


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

0


a source







All Articles