Home >Backend Development >PHP Tutorial >PHP类的继承和接口
PHP类的继承的一些语法
public | 当前类、子类和类外 |
protected | 当前类和子类 |
private | 当前类 |
被final修饰的类 | 只能实例化不能被继承 |
被abstract修饰的类 | 只能被继承不能被实例化 |
注意:
被final修饰的方法不能被子类重写。
self | 当前类本身 |
parent | 当前类父类 |
$this | 当前对象 |
<?php// 定义一个Person类class Person { // 构造函数 public function __construct() { echo "Person's __construct.",'<br />'; } // 析构函数 public function __destruct() { echo "Person's __destruct.",'<br />'; }}// 定义一个PersonMale类继承Person类class PersonMale extends Person { // 构造函数 public function __construct() { echo "PersonMale's __construct.",'<br />'; // 调用父类的构造函数 parent::__construct(); } // 析构函数 public function __destruct() { parent::__destruct(); echo "PersonMale's __destruct.",'<br />'; }}// 定义一个PersonFemale类继承Person类class PersonFemale extends Person{ // 构造函数 public function __construct() { echo "PersonFemale's __construct.",'<br />'; parent::__construct(); } // 析构函数 public function __destruct() { parent::__destruct(); echo "PersonFemale's __destruct.",'<br />'; }}$personObject = new Person();$personMaleObject = new PersonMale();$PersonFemaleObject = new PersonFemale();运行结果:Person's __construct. PersonMale's __construct.Person's __construct. PersonFemale's __construct.Person's __construct. Person's __destruct.PersonFemale's __destruct. Person's __destruct.PersonMale's __destruct. Person's __destruct.PHP的接口
<?php/** * 接口MyInterFaceA */interface MyInterFaceA { public function functionA(); public function functionB();}/** * 接口MyInterFaceB */interface MyInterFaceB { public function functionC(); public function functionD();}/** * 类实现接口MyInterFaceA和MyInterFaceB * 并且重写接口里所有的公共的抽象方法 */class MyClass implements MyInterFaceA,MyInterFaceB{ public function functionA() { } public function functionB() { } public function functionC() { } public function functionD() { }}