This article is about abstract classes, interfaces and traits in PHP. Now I share it with you. Friends in need can also read the content of this article for reference.
Manual reference: http://php.net/manual/zh/language.oop5.abstract.php
Definition: PHP 5 supports abstract classes and abstract methods. Classes defined as abstract cannot be instantiated. Any class must be declared abstract if at least one method in it is declared abstract. AndWhen inheriting an abstract class, the subclass must define all abstract methods in the parent class (constants can be defined in the abstract class);
Keywords: abstract
<?php abstract class AbstractClass { const NAME='张三'; // 强制要求子类定义这些方法 abstract protected function getValue(); abstract protected function prefixValue($prefix); // 普通方法(非抽象方法) public function printOut() { print $this->getValue() . "\n"; } } class ConcreteClass1 extends AbstractClass { protected function getValue() { return "ConcreteClass1".self::NAME; } public function prefixValue($prefix) { return "{$prefix}ConcreteClass1"; } } $class1 = new ConcreteClass1; $class1->printOut(); echo $class1->prefixValue('FOO_') ."\n";
Keywords: interface
interface test1{ function say(); } interface test2{ function see(); } //接口继承接口 (继承接口时使用extends关键字) interface test3 extends test1,test2 { function sleep(); } //类实现接口(实现接口时使用 implements关键字) class test implements test1,test2{ public function say(){} public function see(){} public function sleep() { echo '休息'; } } //接口中只能有抽象方法(不能定义常量,不能有构造方法,不能有普通方法),且接口类中所有未实现的方法需要在子类中全部实现
Reference address https://www.cnblogs.com/smallrookie/p/6516010.html
Definition :Starting from PHP 5.4.0, PHP has implemented a new code reuse method.
<?php trait A { public function smallTalk() { echo 'a'; } public function bigTalk() { echo 'A'; } } trait B { public function smallTalk() { echo 'b'; } public function bigTalk() { echo 'B'; } } class Aliased_Talker { use A, B { B::smallTalk insteadof A; //使用B类的smallTalk方法(替换A方法) A::bigTalk insteadof B; B::bigTalk as talk;//重命名 B类中的bigTalk方法重命名为talk方法 } } $obj = new Aliased_Talker; $obj->smallTalk(); //b $obj->bigTalk(); //A $obj->talk();//B //trait不能实例化,不能有常量
Related recommendations:
First introduction to php interface
Sharing the characteristics and functions of Trait in PHP
The above is the detailed content of abstract class,interface,trait. For more information, please follow other related articles on the PHP Chinese website!