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?
a source to share
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" :)
a source to share
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.
a source to share
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']
}
}
a source to share
$ this refers to the caller. The PHP docs have good examples and further details.
a source to share