php - 为什么我们必须使用 $this-> 运算符? | PHP

标签 php oop

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

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

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

但是,在例子中我看到 $this-> 是这样使用的:

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

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

最佳答案

$this 引用当前对象。

根据 php.net

The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).

关于php - 为什么我们必须使用 $this-> 运算符? | PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26935563/

相关文章:

python - 将装饰器应用于访问类属性的类方法

c++ - 派生异常不继承构造函数

c# - 哪个声明更好?

javascript - 如果图像源(img src)具有特定的类或 ID,则将查询字符串添加到图像源(img src)

php - 如何只更新选定的 mysql 数据库条目而不弄乱早期的条目

php - Xampp 服务器中的所有 php 项目应该放在哪里?

java - 如何在全局声明HashMap并仅在第一次向其中添加值?

oop - Rust 的正确 OOP 架构是什么?

javascript - 为什么 PHP 没有正确返回我的 JSON?

php - PDO异常 : SQLSTATE 01002 Adaptive Server connection failed (severity 9)