Skip to content
Advertisement

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?

Advertisement

Answer

The problem would also be that if you declared a function foo() and a method foo(), php would have a hard time figuring out which 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” (meaning that you can also have functions outside classes) – has this “feature” 🙂

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement