$this 关键字
本课属于 Coddy PHP 学习旅程的“面向对象编程”单元。第 4 课,共 91 课。
$this 关键字在类的方法中指向当前实例。你可以用它访问和修改当前对象的属性。
下面是一个使用 $this 的类及其方法示例:
<?php
class Car {
public $color;
public $model;
public function honk() {
echo "Beep beep!\n";
}
public function describe() {
echo "I am a " . $this->color . " " . $this->model . "\n";
}
}$this 关键字用于在方法内部引用调用该方法的对象。
创建一个汽车对象并设置属性:
$myCar = new Car();
$myCar->color = "Red";
$myCar->model = "Sedan";现在调用这些方法:
$myCar->honk();
$myCar->describe();输出:
Beep beep!
I am a Red Sedan调用 $myCar->describe() 时,PHP 会自动将 $this 设置为指向 $myCar。这样,方法就知道要访问哪个对象的属性。
如果你还有另一个汽车对象:
$otherCar = new Car();
$otherCar->color = "Blue";
$otherCar->model = "SUV";
$otherCar->describe(); // 我是一辆 Blue SUV。要点:$this 始终指调用该方法的特定对象。每个对象在运行方法时都有自己的上下文。
挑战
简单通过添加名为 displayInfo 的方法来完成 car.php 中的 Car 类。该方法使用 $this 关键字,按以下格式打印汽车的年份、品牌和型号:
"This car is a [year] [make] [model]"
car.php:包含Car类定义的文件,你将在其中添加displayInfo方法driver.php:导入并使用Car类的主执行文件(已锁定)
亲手试试
<?php
require_once 'car.php';
$myCar = new Car();
$myCar->year = 2020;
$myCar->make = "Toyota";
$myCar->model = "Corolla";
$myCar->displayInfo();
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向对象编程中的所有课
自己练习: PHP 在线编译器