Home > Article > Backend Development > PHP inheritance and polymorphism: go hand in hand to write code symphonies
php editor Yuzai will take you to deeply explore the essence of inheritance and polymorphism in PHP, and discuss how to skillfully use these two features in the code to build a more elegant and efficient code structure for your project, and jointly compose A beautiful symphony of code.
1. Inheritance
Inheritance is a code reuse technique that allows one class to inherit properties and methods from another class, thereby reducing duplicate code. The syntax for inheritance is as follows:
class ChildClass extends ParentClass { // 子类属性和方法 }
For example, suppose we have an Animal
class that has name
and age
properties, and a speak()
method. We can create a Dog
class, inherit from the Animal
class, and add a bark()
method.
class Animal { protected $name; protected $age; public function speak() { echo "I am an animal."; } } class Dog extends Animal { public function bark() { echo "Woof!"; } } $dog = new Dog(); $dog->speak(); // 输出 "I am an animal." $dog->bark(); // 输出 "Woof!"
2. Polymorphism
Polymorphism means that a derived class can override the methods of the parent class to achieve different behaviors. The syntax of polymorphism is as follows:
class ChildClass extends ParentClass { public function method() { // 子类方法实现 } }
For example, suppose we have a Shape
class that has a draw()
method. We can create a Circle
class, inherit from the Shape
class, and override the draw()
method to achieve different drawing behaviors.
class Shape { public function draw() { echo "I am a shape."; } } class Circle extends Shape { public function draw() { echo "I am a circle."; } } $shape = new Shape(); $shape->draw(); // 输出 "I am a shape." $circle = new Circle(); $circle->draw(); // 输出 "I am a circle."
Summarize
Inheritance and polymorphism inphp are important concepts in object-oriented programming. They go hand in hand to compose code symphonies and make the code more scalable, reusable and maintainable. Inheritance allows us to reuse code, while polymorphism allows us to write more flexible and extensible code.
The above is the detailed content of PHP inheritance and polymorphism: go hand in hand to write code symphonies. For more information, please follow other related articles on the PHP Chinese website!