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

谁说胖子不能爱 提交于 2019-12-01 12:23:20

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" :)

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.

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

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']
    }
}

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!