Home Backend Development PHP Tutorial Inheritance, polymorphism and interfaces: three major object-oriented features of PHP

Inheritance, polymorphism and interfaces: three major object-oriented features of PHP

May 11, 2023 pm 03:45 PM
interface inherit Polymorphism

PHP is a server-side programming language that supports object-oriented programming (OOP) since PHP5. The core idea of ​​OOP is to encapsulate data and behavior in objects to improve the maintainability and scalability of the program. In PHP, object-oriented programming has three major characteristics: inheritance, polymorphism and interfaces.

1. Inheritance

Inheritance means that one class can inherit properties and methods from another class. The inherited class is called the parent class or base class, and the inherited class is called the subclass or derived class. Subclasses can inherit the properties and methods of the parent class and can override or extend them.

For example, we can define an animal class Animal, which has attributes $name and $color, and methods eat() and sleep(). Then we can define a dog class Dog, which inherits from the Animal class and adds a bark() method:

class Animal {
    protected $name;
    protected $color;
    
    public function eat() {
        echo "$this->name is eating.
";
    }
    
    public function sleep() {
        echo "$this->name is sleeping.
";
    }
}

class Dog extends Animal {
    public function bark() {
        echo "$this->name is barking.
";
    }
}

$dog = new Dog();
$dog->name = "Fido";
$dog->color = "brown";
$dog->eat(); // 输出: Fido is eating.
$dog->sleep(); // 输出: Fido is sleeping.
$dog->bark(); // 输出: Fido is barking.
Copy after login

Note that in the parent class, we use the keyword protected to define the attributes $name and $color. This means that they can only be accessed within parent and child classes and not directly outside the class. In the subclass, we have used the keyword public to define the bark() method, which means it can be accessed both inside and outside the class.

2. Polymorphism

Polymorphism means that an object can appear in multiple forms. In object-oriented programming, polymorphism means that a subclass can replace a parent class without affecting the correctness of the program.

For example, we can define a zoo class Zoo, which has a show($animal) method to display animal information. Now we can pass different animal objects to the show() method to achieve polymorphism:

class Zoo {
    public function show($animal) {
        $animal->eat();
        $animal->sleep();
    }
}

$dog = new Dog();
$dog->name = "Fido";
$dog->color = "brown";

$cat = new Cat();
$cat->name = "Fluffy";
$cat->color = "white";

$zoo = new Zoo();
$zoo->show($dog); // 输出: Fido is eating. Fido is sleeping.
$zoo->show($cat); // 输出: Fluffy is eating. Fluffy is sleeping.
Copy after login

In this example, we have added a new cat class Cat, which inherits from the Animal class and overrides eat ()method. We can pass dog and cat objects to the show() method, and since they are both subclasses of the Animal class, they can achieve polymorphism.

3. Interface

An interface is a specification that defines a set of methods but has no specific implementation. In PHP, a class can implement one or more interfaces to meet specific functional requirements.

For example, we can define an interface Speakable, which has a speak() method for outputting animal sounds. Then we can let the dog and cat classes implement this interface:

interface Speakable {
    public function speak();
}

class Dog extends Animal implements Speakable {
    public function bark() {
        echo "$this->name is barking.
";
    }
    
    public function speak() {
        $this->bark();
    }
}

class Cat extends Animal implements Speakable {
    public function meow() {
        echo "$this->name is meowing.
";
    }
    
    public function speak() {
        $this->meow();
    }
}

$dog = new Dog();
$dog->name = "Fido";
$dog->color = "brown";
$dog->speak(); // 输出: Fido is barking.

$cat = new Cat();
$cat->name = "Fluffy";
$cat->color = "white";
$cat->speak(); // 输出: Fluffy is meowing.
Copy after login

In this example, we define a Speakable interface, which has a speak() method. Then we let the Dog and Cat classes implement this interface and implement the speak() method respectively. This way we can call the speak() method on dog and cat objects without knowing their specific implementation.

Inheritance, polymorphism and interfaces are the three major features of PHP object-oriented programming. They allow us to better organize and manage code and improve code reusability and scalability. Understanding these features can give us a deeper understanding of PHP's object-oriented programming model.

The above is the detailed content of Inheritance, polymorphism and interfaces: three major object-oriented features of 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

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

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.

See all articles