在继承的过程中,有时子类需要覆盖父类中的方法或属性,但又需要保留父类原有的内容。这时,可以使用parent::关键字来调用父类的方法或属性。下面是一个示例代码:
class Person {protected $name;public function __construct($name) {$this->name = $name;}public function sayHello() {echo "Hello, my name is ".$this->name;} } class Student extends Person {public function sayHello() {parent::sayHello();echo ", I am a student.";} } $student = new Student('Tom'); $student->sayHello();
在上面的代码中,我们定义了一个Person类和一个Student类。Student继承了Person类,并且覆盖了父类中的sayHello()方法,但我们也需要在子类中调用父类的sayHello()方法。这时,我们使用了parent::关键字来调用父类的sayHello()方法,并在其后面加上子类独有的内容“,I am a student.”。当我们执行这个代码时,输出的结果为“Hello, my name is Tom, I am a student.”
另一个使用parent::的情况是在构造函数中。当我们在子类中定义一个构造函数时,如果想要调用父类的构造函数来初始化父类的属性,我们可以使用parent::来实现。以下是一个示例代码:
class Person {protected $name;public function __construct($name) {$this->name = $name;} } class Student extends Person {protected $grade;public function __construct($name, $grade) {parent::__construct($name);$this->grade = $grade;} } $student = new Student('Tom', 90); echo $student->name." got a grade of ".$student->grade;
在上面的代码中,我们定义了一个Person类和一个Student类。Student继承了Person类,并且在构造函数中覆盖了父类的构造函数,但我们也需要在子类中调用父类的构造函数来初始化父类的属性。这时,我们使用了parent::__construct($name)来调用父类的构造函数,在__construct()的参数中传入了$name,从而初始化了父类中的属性。当我们执行这个代码时,输出的结果为“Tom got a grade of 90”。
除了在子类中调用父类中的方法和构造函数之外,parent::还可以用于调用父类的静态方法和常量。以下是一个示例代码:
class Person {const MESSAGE = "Hello";public static function sayHello() {echo self::MESSAGE;} } class Student extends Person {public static function sayHello() {parent::sayHello();echo ", I am a student.";} } Student::sayHello();
在上面的代码中,我们定义了一个Person类和一个Student类。Person类中定义了一个常量MESSAGE和一个静态方法sayHello(),Student类继承了Person类,并在sayHello()方法中用parent::来调用父类的sayHello()方法,从而输出了“Hello, I am a student.”的语句。当我们执行这个代码时,输出的结果为“Hello, I am a student.”。
综上所述,parent是在PHP中用于继承中调用父类的方法、构造函数、常量和静态方法的关键字。通过使用parent::,我们可以更加灵活地组织和重复利用代码。