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

后端 未结 5 1978
你的背包
你的背包 2021-01-16 04:24

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

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-16 04:44

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

提交回复
热议问题