* Abstract class
* 1. Use keywords: abstract
* 2. As long as there is a method in the class declared as abstract abstract method, then this class must be declared as abstract class
* 3. Abstract methods are only allowed to have method declarations and parameter lists, and method bodies are not allowed;
* 4. Because of the uncertainty of abstract methods, instantiation of abstract classes is prohibited. Only instantiation through inheritance is allowed;
* 5. In a subclass that inherits an abstract class, all abstract methods in the abstract class must be implemented
* 6. Access to subclass members The restriction level must be equal to or less than the contract of the abstract class. For example, if the abstract class is protected, the subclass must be
* protected or public. Private
is not allowed * 7. Subclass method parameters must be the same as The parameters of the abstract class method are exactly the same, but the default parameters are allowed
* Special attention
* 1. Although the abstract class cannot be instantiated, you can still create a constructor for it, but it must be declared as final
* 2. In theory, abstract classes should not have static members. Some editors will prompt E_STRICT2048, but you can still do this.
abstract class Fruits { //水果名称 protected $name; //声明静态属性,因为要用到静态类中 // protected static $name; //抽象方法 abstract public function eat(); //静态抽象方法 // abstract static public function eat(); //尽管不能直接实例化抽象类,但仍然可以有构造方法 public function __construct() { return '抽象类构造器,实例化时自动调用<br>'; } }
//For the convenience of teaching, abstract classes are and its subclasses are all written in one class file
//In actual development, an independent class file should be created for each class
class Apple extends Fruits { protected $name = '苹果'; //声明为静态属性 // public static $name = '苹果'; public function eat() { return $this->name.'可以直接生吃'; } //子类构造方法 public function __construct() { echo parent::__construct(); } //实现抽象类中的抽象静态方法eat() // public static function eat() // { // return self::$name.'可以直接生吃'; // } } $apple = new Apple; echo $apple->eat();
//It was an abstract static class before, no need Instantiation, you can use the class to directly access
//echo Apple::eat();
The above is the detailed content of abstract class in php. For more information, please follow other related articles on the PHP Chinese website!