PHP OOP-抽象
时间:2020-02-23 14:42:02 来源:igfitidea点击:
在本教程中,我们将学习有关PHP中的抽象的知识。
什么是抽象?
在OOP中,抽象是一个概念,其中类具有没有实现的方法。
这个想法是要有一个模板,并让继承父类的子类实现该方法。
如何创建抽象方法?
当我们想创建一个抽象方法时,我们在方法名称前使用关键字"抽象"。
如果一个类有一个抽象方法,那么我们还要在该类之前添加abstract
关键字。
在下面的示例中,我们有一个抽象方法foo(),因此我们向该类添加了abstract关键字。
abstract class Sample { //abstract method public abstract function foo(); }
创建抽象类时,实际上是在创建模板。
我们无法实例化一个抽象类
由于抽象类只是一个没有完全实现的方法的模板,因此不允许创建其对象。
//abstract class abstract class Sample { } //this will give error - can't create object of an abstract class $obj = new Sample();
抽象类可以具有完全实现的方法
允许在抽象类中具有完全实现的方法。
在下面的示例中,我们有一个抽象类Sample,带有一个抽象方法foo()和完全实现的方法hello()。
//abstract class abstract class Sample { //abstract method public abstract function foo(); //method public function hello() { printf("Hello World!"); } }
继承一个抽象类
当子类继承抽象类时,父类的抽象方法必须在子类中实现。
如果子类未实现父类的抽象方法,则必须将子类声明为抽象。
子类实现抽象方法
在下面的示例中,我们有一个抽象的父类" Sample",具有一个抽象方法" foo()"和" add()"。
我们有一个子类Po,它扩展了父类Sample并实现了抽象方法foo()和add()。
//abstract parent class abstract class Sample { //abstract method public abstract function foo(); public abstract function add($x, $y); } //child class class Po extends Sample { //implementing abstract methods of parent class public function foo() { printf("Hello World!"); } public function add($x, $y) { return ($x + $y); } } //create object of the Po class $obj = new Po(); $obj->foo(); //this will print "Hello World!" $sum = $obj->add(10, 20); //this will return 30 printf("Sum = %d", $sum); //this will print "Sum = 30"
子类未实现抽象方法
子类不必实现父类的抽象方法。
如果子类未实现父类的抽象方法,则必须将子类声明为抽象。
在下面的示例中,我们有一个具有抽象方法foo()和hello()的父类Sample。
我们有一个子类Po,它扩展了父类,只实现了抽象方法hello(),没有实现抽象方法foo()。
由于子类Po具有一个未实现的抽象方法foo(),因此我们必须将类Po声明为抽象类。
//abstract parent class abstract class Sample { //abstract method public abstract function foo(); public abstract function hello(); } /** * child class Po set to abstract * as it is not implementing the abstract method foo() */ abstract class Po extends Sample { //implemented method public function hello() { printf("Hello World!"); } }