Home Backend Development PHP Tutorial How to use inheritance, polymorphism and interfaces in PHP

How to use inheritance, polymorphism and interfaces in PHP

Jun 23, 2023 am 11:49 AM
interface inherit Polymorphism

PHP is an open source scripting language for server-side programming and has become one of the most popular and widely used programming languages ​​in the world. In PHP, inheritance, polymorphism, and interfaces are three important object-oriented programming concepts that allow developers to gain great advantages in code reuse, flexibility, and maintainability. This article will delve into these three concepts and introduce how to use them in PHP.

  1. Inheritance

Inheritance is one of the most basic concepts in object-oriented programming. It means that a class can inherit the properties and methods of another class and add custom properties and methods on this basis. Subclassing is achieved by extending a parent class (also called a superclass or base class), allowing the subclass to reuse the parent class's code and functionality.

In PHP, inheritance is done by using the keyword "extends". For example, the following code is a simple inheritance implementation:

class Person {
  // 定义一个方法
  public function sayHello() {
    echo "Hello, world!";
  }
}

class Student extends Person {
  // 定义一个新的方法
  public function sayGoodbye() {
    echo "Goodbye, world!";
  }
}

// 使用子类的对象
$student = new Student();
$student->sayHello();  // 输出 “Hello, world!”
$student->sayGoodbye();  // 输出 “Goodbye, world!”
Copy after login

In this example, we define a class named Person and define a method named sayHello() in it. We then created a subclass called Student and extended it to the Person class using the "extends" keyword. In the subclass, we added a new method called sayGoodbye(). Finally, we create an instance of the Student class named $student and call its methods.

It should be noted that when a subclass inherits a parent class, it can not only inherit its properties and methods, but also access non-private properties and methods. In fact, for private properties and methods, subclasses cannot access them even after inheriting from the parent class.

  1. Polymorphism

Polymorphism is another key object-oriented programming concept. It refers to the fact that the same method can behave differently under different circumstances. Behavior. Methods with polymorphism can automatically determine the actual method that should be called at runtime, which greatly improves the flexibility and scalability of the program.

In PHP, the way to achieve polymorphism is to use the keywords "abstract" and "interface". We can achieve polymorphism by defining abstract classes or interfaces and inheriting abstract classes or implementing interfaces.

2.1 Abstract class

An abstract class is a class that cannot be instantiated and can only be inherited as a superclass of other classes. An abstract class can define some abstract methods, which must be implemented in its subclasses. In this way we can achieve polymorphism through abstract classes.

The following is an example of using abstract classes to achieve polymorphism:

abstract class Shape {
  // 定义一个抽象方法
  abstract public function getArea();
}

class Circle extends Shape {
  private $radius;

  public function __construct($radius) {
    $this->radius = $radius;
  }

  // 实现抽象方法
  public function getArea() {
    return pi() * pow($this->radius, 2);
  }
}

class Square extends Shape {
  private $side;

  public function __construct($side) {
    $this->side = $side;
  }
  
  // 实现抽象方法
  public function getArea() {
    return pow($this->side, 2);
  }
}

// 创建一个圆
$circle = new Circle(2);
// 创建一个正方形
$square = new Square(2);

// 输出面积
echo $circle->getArea();  // 输出 "12.566370614359"
echo $square->getArea();  // 输出 "4"
Copy after login

In this example, we define an abstract class Shape and declare an abstraction named getArea() method. Then, we created two subclasses, Circle and Square, and implemented the getArea() method respectively. Finally, we create instances of a circle and a square and call their getArea() methods.

2.2 Interface

An interface is an abstract type that defines a set of method signatures (but does not implement these methods). A class can implement this interface to express the behavior defined by this interface. a commitment. In this way we can achieve polymorphism through interfaces as well. In PHP, we can use the keyword "interface" to define the interface and the keyword "implements" to implement the interface.

The following is an example of using interfaces to achieve polymorphism:

interface Animal {
  public function makeSound();
}

class Dog implements Animal {
  public function makeSound() {
    echo "Woof!";
  }
}

class Cat implements Animal {
  public function makeSound() {
    echo "Meow!";
  }
}

// 创建一个狗
$dog = new Dog();
// 创建一只猫
$cat = new Cat();

// 输出声音
$dog->makeSound();  // 输出 "Woof!"
$cat->makeSound();  // 输出 "Meow!"
Copy after login

In this example, we define an interface Animal and declare a method named makeSound(). Then, we created two subclasses Dog and Cat that implemented the Animal interface, and implemented the makeSound() method respectively. Finally, we create instances of a dog and a cat and call their makeSound() methods.

It should be noted that interfaces can only define abstract methods, and these methods must be implemented by classes that implement the interface.

  1. Summary

Inheritance, polymorphism and interface are three important object-oriented programming concepts, which are also widely used in PHP. Using inheritance, we can let one class inherit properties and methods from another class and add custom properties and methods on top of that. Using polymorphism, we can call methods with different behaviors through the same method name in different situations. Using an interface, you can define a set of method signatures and have these methods implemented by classes that implement the interface.

When we write PHP object-oriented programs, reasonable use of the three concepts of inheritance, polymorphism and interfaces can make our programs more flexible, scalable and easier to maintain.

The above is the detailed content of How to use inheritance, polymorphism and interfaces in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of C++ function inheritance: How to use 'base class pointer' and 'derived class pointer' in inheritance? Detailed explanation of C++ function inheritance: How to use 'base class pointer' and 'derived class pointer' in inheritance? May 01, 2024 pm 10:27 PM

In function inheritance, use "base class pointer" and "derived class pointer" to understand the inheritance mechanism: when the base class pointer points to the derived class object, upward transformation is performed and only the base class members are accessed. When a derived class pointer points to a base class object, a downward cast is performed (unsafe) and must be used with caution.

What are the internal interfaces of a computer motherboard? Recommended introduction to the internal interfaces of a computer motherboard What are the internal interfaces of a computer motherboard? Recommended introduction to the internal interfaces of a computer motherboard Mar 12, 2024 pm 04:34 PM

When we assemble the computer, although the installation process is simple, we often encounter problems in the wiring. Often, users mistakenly plug the power supply line of the CPU radiator into the SYS_FAN. Although the fan can rotate, it may not work when the computer is turned on. There will be an F1 error "CPUFanError", which also causes the CPU cooler to be unable to adjust the speed intelligently. Let's share the common knowledge about the CPU_FAN, SYS_FAN, CHA_FAN, and CPU_OPT interfaces on the computer motherboard. Popular science on the CPU_FAN, SYS_FAN, CHA_FAN, and CPU_OPT interfaces on the computer motherboard 1. CPU_FANCPU_FAN is a dedicated interface for the CPU radiator and works at 12V

Common programming paradigms and design patterns in Go language Common programming paradigms and design patterns in Go language Mar 04, 2024 pm 06:06 PM

As a modern and efficient programming language, Go language has rich programming paradigms and design patterns that can help developers write high-quality, maintainable code. This article will introduce common programming paradigms and design patterns in the Go language and provide specific code examples. 1. Object-oriented programming In the Go language, you can use structures and methods to implement object-oriented programming. By defining a structure and binding methods to the structure, the object-oriented features of data encapsulation and behavior binding can be achieved. packagemaini

C++ virtual function table and polymorphic implementation, how to avoid memory waste C++ virtual function table and polymorphic implementation, how to avoid memory waste May 31, 2024 pm 07:03 PM

Virtual base classes optimize vtable memory overhead by allowing inheritance from multiple base classes without creating additional vtables. In the optimized code, the shape base class no longer has a virtual function table, and the circle and rectangle classes share the same virtual function table, thus reducing memory consumption.

Introduction to PHP interfaces and how to define them Introduction to PHP interfaces and how to define them Mar 23, 2024 am 09:00 AM

Introduction to PHP interface and how it is defined. PHP is an open source scripting language widely used in Web development. It is flexible, simple, and powerful. In PHP, an interface is a tool that defines common methods between multiple classes, achieving polymorphism and making code more flexible and reusable. This article will introduce the concept of PHP interfaces and how to define them, and provide specific code examples to demonstrate their usage. 1. PHP interface concept Interface plays an important role in object-oriented programming, defining the class application

How do inheritance and polymorphism affect class coupling in C++? How do inheritance and polymorphism affect class coupling in C++? Jun 05, 2024 pm 02:33 PM

Inheritance and polymorphism affect the coupling of classes: Inheritance increases coupling because the derived class depends on the base class. Polymorphism reduces coupling because objects can respond to messages in a consistent manner through virtual functions and base class pointers. Best practices include using inheritance sparingly, defining public interfaces, avoiding adding data members to base classes, and decoupling classes through dependency injection. A practical example showing how to use polymorphism and dependency injection to reduce coupling in a bank account application.

Detailed explanation of C++ function inheritance: How to debug errors in inheritance? Detailed explanation of C++ function inheritance: How to debug errors in inheritance? May 02, 2024 am 09:54 AM

Inheritance error debugging tips: Ensure correct inheritance relationships. Use the debugger to step through the code and examine variable values. Make sure to use the virtual modifier correctly. Examine the inheritance diamond problem caused by hidden inheritance. Check for unimplemented pure virtual functions in abstract classes.

Detailed explanation of C++ function inheritance: How to understand the 'is-a' and 'has-a' relationship in inheritance? Detailed explanation of C++ function inheritance: How to understand the 'is-a' and 'has-a' relationship in inheritance? May 02, 2024 am 08:18 AM

Detailed explanation of C++ function inheritance: Master the relationship between "is-a" and "has-a" What is function inheritance? Function inheritance is a technique in C++ that associates methods defined in a derived class with methods defined in a base class. It allows derived classes to access and override methods of the base class, thereby extending the functionality of the base class. "is-a" and "has-a" relationships In function inheritance, the "is-a" relationship means that the derived class is a subtype of the base class, that is, the derived class "inherits" the characteristics and behavior of the base class. The "has-a" relationship means that the derived class contains a reference or pointer to the base class object, that is, the derived class "owns" the base class object. SyntaxThe following is the syntax for how to implement function inheritance: classDerivedClass:pu

See all articles