为什么我们必须使用 $this-> 操作符?| PHP

Ash*_*ngh 2 php oop

我正在用 PHP 开发一个应用程序。我试图弄清楚 $this-> 的用法以及为什么它总是首选。

我的意思是我们可以简单地使用此代码在方法中回显属性值

<?php
class place{
    public $country;
    public function countryName($country){
        echo $country;
    }
}
$info = new place();
$info->countryName("Nepal");
?>
Run Code Online (Sandbox Code Playgroud)

但是,在示例中,我看到 $this-> 以这种方式使用:

<?php
class place{
    public $country;
    public function countryName($country){
        $this->country = $country;
        echo $this->country;
    }
}
$info = new place();
$info->countryName("Nepal");
?>
Run Code Online (Sandbox Code Playgroud)

使用 $this-> 是首选还是第一种方法完全正常?

for*_*une 5

$this 正在引用当前对象。

根据 php.net

当从对象上下文中调用方法时,伪变量 $this 可用。$this 是对调用对象的引用(通常是该方法所属的对象,但也可能是另一个对象,如果该方法是从辅助对象的上下文中静态调用的)。