This article mainly introduces object-oriented inheritance in PHP, which has certain reference value. Now I share it with everyone. Friends in need can refer to it
Inheritance
The subclass inherits all the parent class’s-public and protected properties and methods.
Use the keyword extends
Inheritance. One class integrates another and cannot inherit more than one.
子类、父类、基类、超类、派生类
Subclass, derived class——> Class inherited from the base class;
Parent class, base class, super class refers to——> ; Inherited class.
<?php class Father { public $a = 'public'; protected $b = 'protected'; private $c = 'private'; public function func1() { echo 'This is public function','<br/>'; } protected function func2() { echo 'This is protected function','<br/>'; } private function func3() { echo 'This is private function','<br/>'; } } // 继承父类 class Child extends Father { // 子类中调用继承来的方法 public function test() { $this -> func1(); $this -> func2(); //$this -> func3(); 私有方法不可以调用 } } // 实例化子类 $son = new Child(); // 尝试调用属性 echo $son -> a,'<br/>'; //echo $son->b; 不能直接输出b //echo $son -> c; 继承都没继承,当然不能输出 // 尝试调用方法 //$son -> func1(); //$son -> func2(); 不能在类外调用func2 //$son -> func3(); 继承都没继承,当然不能调用 // 间接调用继承自父类的普通方法 $son -> test();
Rewrite
1) Inherit the method of the parent class, and the definition in the subclass is the same as that of the parent class Method with the same name in class , and has the same number of parameters ;
2) When the subclass overrides the method in the parent class, PHP will not call the method in the parent class Overridden method;
3) Whether to call the method of the parent class depends on the subclass.
4) When implementing method coverage, the access modifier can be different , but the access scope of the subclass must be greater than or equal to the parent class Access scope .
parent:: 访问父类中被重写的属性和方法
<?php class Father { public function shuo($num) { echo 'a a o o'; } } class Son extends Father { public function shuo($num) { // 调用父类中被重写的方法 // parent::shuo($num); echo 'Hello World'; } public function test($num) { parent::shuo($num); } } // 实例化子类 $son1 = new Son(); $son1 -> shuo(1); // Hello World $son1 -> test(1); // a a o o
final keyword
If the method in the parent class is declared final, then Subclasses cannot override this method.
If a class is declared final, it cannot be inherited.
<?php class Father { final public function test() { echo 'hello'; } } class Son extends Father { public function test() { echo '你好'; } } // 实例化子类 $son1 = new Son(); $son1 -> test(); // 报错,函数不能被重写
Related recommendations:
php object-oriented overloading
php object-oriented Encapsulation
The above is the detailed content of PHP object-oriented inheritance. For more information, please follow other related articles on the PHP Chinese website!