PHP OOP-继承
时间:2020-02-23 14:42:02 来源:igfitidea点击:
在本教程中,我们将学习有关PHP中的继承的知识。
什么是继承?
在面向对象编程中,当一个类从另一个类派生其属性和方法时,则称为继承。
派生属性和方法的类称为子类或者子类。
发生继承的类称为超类或者父类。
我们使用extends关键字从父类继承。
在下面的示例中,我们有父类Vehicle。
我们正在创建从父类继承的子类Car。
//parent class
class Vehicle {
private $color;
public function setColor($color) {
$this->color = $color;
}
public function getColor() {
return $this->color;
}
}
//child class
class Car extends Vehicle {
private $steeringWheel;
public function setSteeringWheel($steeringWheel) {
$this->steeringWheel = $steeringWheel;
}
public function getSteeringWheel() {
return $this->steeringWheel;
}
}
//object of the child class
$obj = new Car();
//set property
$obj->setColor("Black");
$obj->setSteeringWheel("Leather");
//get property
$color = $obj->getColor();
$steeringWheel = $obj->getSteeringWheel();
//this will output "Color = Black and SteeringWheel = Leather"
printf("Color = %s and SteeringWheel = %s", $color, $steeringWheel);
可以继承的属性和方法
公共和受保护的属性和方法可以从父类继承到子类。
私有属性和方法不能被继承。
方法重写
在OOP中,当子类具有与父类同名的方法时,这称为父类方法的重写。
当子类的对象调用该方法时,将执行子类方法而不是父类方法。
在下面的示例中,我们有一个父类" Foo",它被子类" Po"继承。
父类具有方法" hello()",该方法在子类Po中被覆盖。
//parent class
class Foo {
//method
public function display() {
printf("class Foo method display...");
}
public function hello() {
printf("class Foo method hello...");
}
}
//child class
class Po extends Foo {
//override hello - parent method
public function hello() {
printf("class Po method hello... method hello() overridden...");
}
}
//object of parent class Foo
$foo_obj = new Foo();
$foo_obj->display(); //this will print "class Foo method display..."
$foo_obj->hello(); //this will print "class Foo method hello..."
//object of child class Po
$po_obj = new Po();
$po_obj->hello(); //this will print "class Po method hello... method hello() overridden..."
调用重写的父方法
要从子类调用父类的重写方法,我们使用parent关键字,后跟::运算符,然后使用方法名称。
//parent class
class Foo {
public function hello() {
printf("class Foo method hello...");
}
}
//child class
class Po extends Foo{
//overriding parent method
public function hello() {
printf("class Po method hello...");
//calling parent method
parent::hello();
}
}
//creating child class object
$po_obj = new Po();
/**
* this will print
* "class Po method hello..."
* "class Foo method hello..."
*/
$po_obj->hello();
防止类被继承
为了防止类被继承,我们使用final关键字。
final class Sample {
}
//this will cause error - can't inherit final class
class Foo extends Sample {
}
防止方法被重写
为了防止类方法被覆盖,我们在函数之前使用final关键字。
//parent class
class Sample {
//final method
public final function hello() {
}
}
//child class
class Po extends Sample {
//this will given error - can't override final method
public function hello() {
}
}

