PHP中 this、self 和 parent 关键字详解
在PHP面向对象编程中,this、self和parent是三个极易混淆的关键字。它们分别代表当前对象实例、当前类和父类的引用。正确使用这三个关键字能够清晰地管理作用域,避免属性与方法调用错误。
结果或目标
明确区分 this、self 和 parent 的作用范围,掌握它们在实例化对象、调用静态成员以及继承结构中的正确用法。
准备条件
具备 PHP 基础语法知识,了解类(Class)、对象(Object)和继承(Inheritance)的基本概念。确保开发环境支持 PHP 5 及以上版本(注:虽为老教程风格,但核心机制在现代 PHP 8 中依然完全兼容)。
第1步:理解 this 关键字 - 指向当前对象实例
this 是一个自动全局变量,它指向调用该方法的当前对象实例。它可以访问对象的所有可见属性和方法(包括私有和非静态的)。
- 目的:在类的方法内部操作当前实例的数据。
- 入口:任何非静态方法中。
- 动作:使用
$this->属性名访问实例属性。
<?php
class UserName {
private $name;
// 构造函数中使用 this
function __construct($name) {
$this->name = $name;
}
// 打印用户名成员函数
function printName() {
print($this->name);
}
}
// 实例化第一个对象
$nameObject = new UserName("heiyeluren");
$nameObject->printName(); // 输出: heiyeluren
// 重新赋值,再次运行
$nameObject = new UserName("PHP");
$nameObject->printName(); // 输出: PHP
?>
在上述代码中,当执行 $nameObject->printName() 时,$this 就自动指向了 $nameObject 这个具体的对象实例。因此,$this->name 等同于 $nameObject->name。每次实例化一个新的对象,$this 都会指向那个新的实例。
第2步:理解 self 关键字 - 指向当前类本身
self 指向的是定义它的类本身,而不是类的某个实例。它通常用于访问类的静态成员(属性或方法)。调用静态成员时,必须使用作用域解析运算符 ::。
- 目的:在类内部引用自身的静态资源,不依赖于对象实例。
- 入口:类定义的任何方法(包括静态和非静态方法)中。
- 重要参数:必须搭配
::使用,即self::$属性名或self::方法名()。
<?php
class Counter {
// 静态变量,属于类而非具体实例
private static $firstCount = 0;
private $lastCount;
function __construct() {
// 使用 self 访问静态变量,注意使用 ::
$this->lastCount = ++self::$firstCount;
}
function printLastCount() {
print($this->lastCount);
}
}
$countObject = new Counter();
$countObject->printLastCount(); // 输出: 1
?>
注意代码中 self::$firstCount 的用法。因为 $firstCount 是 static 定义的,它与特定的对象无关,而是归属于 Counter 类本身。所以不能用 $this->firstCount 来调用,必须用 self::$firstCount。
第3步:理解 parent 关键字 - 指向父类
parent 指向当前类的直接父类。它最常见的用途是在子类的构造函数中调用父类的构造函数,以确保父类的初始化逻辑被正确执行。
- 目的:在子类中复用或显式调用父类的方法和构造逻辑。
- 入口:子类(派生类)的方法中。
- 动作:使用
parent::方法名(),特别是parent::__construct()。
<?php
// 基类
class Animal {
public $name;
public function __construct($name) {
$this->name = $name;
}
}
// 派生类
class Person extends Animal {
public $personSex;
public $personAge;
function __construct($personSex, $personAge) {
// 使用 parent 调用父类的构造函数进行初始化
parent::__construct("heiyeluren");
$this->personSex = $personSex;
$this->personAge = $personAge;
}
function printPerson() {
print($this->name . " is " . $this->personSex . ", this year " . $this->personAge);
}
}
// 实例化 Person 对象
$personObject = new Person("male", "25");
$personObject->printPerson(); // 输出: heiyeluren is male, this year 25
?>
在 Person 类中,通过 parent::__construct("heiyeluren"),我们调用了 Animal 类的构造函数,将 $name 初始化为 "heiyeluren"。由于 $name 在父类中被定义为 public,子类可以通过 $this->name 直接访问该属性。
完成判断
如果代码能够无报错地编译运行,且输出的变量值符合预期(例如 this 对应实例数据,self 对应静态类数据,parent 成功执行了父类初始化),则表明已正确掌握这三个关键字的使用场景。
简要总结
this 是指向对象实例的一个指针,用于访问实例属性和方法;self 是对类本身的一个引用,专门用于访问静态成员,需配合 :: 使用;parent 是对父类的引用,常用于继承体系中调用父类的方法。理清这三者的作用域边界,是写出整洁、健壮 PHP 面向对象代码的基础。以上就是PHP中 this、self 和 parent 关键字详解的详细内容,更多关于PHP面向对象技术的资料请关注本站其它相关文章!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









