为什么我们必须使用$ this->运营商? | PHP

时间:2014-11-14 17:26:47

标签: php oop

我正在用PHP开发一个应用程序。我试图找出使用$ this->以及为什么总是首选。

我的意思是我们可以使用此代码

简单地回显方法中的属性值
<?php
class place{
    public $country;
    public function countryName($country){
        echo $country;
    }
}
$info = new place();
$info->countryName("Nepal");
?>

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

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

是否使用$ this-&gt;首选方法还是第一种完全正常的方法?

7 个答案:

答案 0 :(得分:4)

$this正在引用当前对象。

根据php.net

  

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

答案 1 :(得分:3)

$this->country 

是相对于班级的国家

$country 

是相对于方法

答案 2 :(得分:2)

$this->country会回显您的班级$country,而只有echo $country会回显您的方法级$country。这完全是因为对象在PHP中的工作方式以及变量的范围。随着你一直在寻找,你会看到更多的使用

答案 3 :(得分:2)

第一个弧不回显一个属性,它只是回显传入的值。

第二个弧将传入的值分配给属性,然后使用$ this-&gt; country来回显该属性。

如果您在第一个弧线中回显$ this-&gt;国家/地区,那么您将得不到回音。

答案 4 :(得分:2)

$this-> 

帮助您引用类变量。

例如:

   public function countryName($country){
         $this->country = $country;
        echo $this->country;
    }

您的$this->country指的是类var,需要将其设置为参数$country

答案 5 :(得分:2)

$this表示该类的任何实例。因此,当您创建对象$USA并致电countryName($country)时,$this将代表对象$USA

<?php
$USA = new place();
$USA->countryName("USA");
?>

在您的代码中,您正在回显函数countryName($country)的参数,但不回显类属性,但在此处:

<?php
class place{
    public $country;//This is the class attribute.
    public function countryName($country){
        $this->country = $country;/*here you are storing the value of the parameter passed to the function into the class attribute ($this->country)*/
        echo $this->country;
    }
}
?>

答案 6 :(得分:0)

使用$this->country$country的优势在于,您也可以在其他地方使用$this->country。该值存储在对象$info中。

例如:

// #1 case
class place {
  public $country; // This is not used
  public function countryName($country) {
    echo $country;
  }
}

$info = new place();
$info->countryName("Nepal");
// Result:
//   Nepal


// #2 case: Using $this
class place {
  public $country; // This is not used
  public function countryName($country) {
    $this->country = $country;
    echo $this->country;
  }
  public function whereAmI() { // NO parameters
    echo 'You are in the country "' . $this->country . '"';
  }
}

$info = new place();
$info->countryName("Nepal");
$info->whereAmI();
// Result:
//   Nepal
//   You are in the country "Nepal"