Home  >  Article  >  Backend Development  >  How to understand abstract classes and abstract methods in PHP? (with code)

How to understand abstract classes and abstract methods in PHP? (with code)

不言
不言Original
2018-07-21 17:12:082525browse

Today I will talk to you about abstract classes and abstract methods in object-oriented PHP. To put it simply, an abstract class in PHP is a class that cannot be instantiated and can only be used as the parent class of other classes. To use, abstract methods cannot bring method bodies. Let’s take a look at specific examples.

Object-oriented abstract methods and abstract classes:

All subclasses must inherit the methods of the parent class, but there is uncertainty when inheriting, and the methods of the parent class must be modified. Rewriting, at this time we define the overridden method as an abstract method. Abstract methods do not need to have a method body. This class is also abstract abstract.

Abstract class is a class that cannot be instantiated and can only be used as a parent class of other classes!

If a method in a class is abstract, then the class is an abstract class.

If a class is an abstract class, the class must be modified with abstract.

Abstract class is a special class, interface is a special abstract class, polymorphism requires the use of abstract classes or interfaces!

The test code is as follows:

abstract class A{
	public $name = 'zym';
	abstract function show();
}
//$a = new A();//会报错
class B extends A{
	public function show(){
		echo '继承父类的抽象方法并进行重写';
	}
}
$b = new B();
$b->show();

Abstract classes are similar to ordinary classes, including member variables and member methods. The difference between the two is that an abstract class must contain at least one abstract method, and an abstract method has no methods. body, the implementation of its functions can only be completed in subclasses.

The code is as follows:

//定义一个名为【交通工具】的类
abstract class Vehicle{
	private $name;//名称
	private $price;//价格
	private $brand;//品牌
	abstract function run();
}
class Truck extends Vehicle{
	function run(){
		echo '卡车在路上跑';
	}
}
class Plane extends Vehicle{
	public function run(){
		echo '飞机在天上飞';
	}
}
$plane = new Plane;
$plane->run();

Note: Abstract methods must not have method bodies!

Related recommendations:

Analysis on the concepts and usage of abstract classes and abstract methods in PHP, PHP abstraction

detailed explanation in PHP Abstract methods and abstract classes

The above is the detailed content of How to understand abstract classes and abstract methods in PHP? (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn