Home  >  Article  >  Backend Development  >  How to override functions in PHP?

How to override functions in PHP?

WBOY
WBOYOriginal
2024-04-11 11:27:02556browse

Function overriding in PHP involves overriding a method of the same name in the parent class for code reuse, polymorphism and maintenance. Syntax: class Subclass extends Superclass { public function overridenMethod() { // Custom implementation } }. The overridden function signature must be consistent with that in the parent class; it is recommended to add the @override annotation to improve readability; the parent:: syntax allows access to the original implementation of the parent class method.

如何在 PHP 中重写函数?

How to override functions in PHP

PHP allows you to override functions by overriding the method of the same name in the parent class. This is very useful in object-oriented programming, enabling code reuse, polymorphism, and code maintenance.

Syntax

class Subclass extends Superclass {
    public function overridenMethod() {
        // 自定义实现
    }
}

Practice

Suppose we have a Animal class, containing a speak() method, this method prints a general message. Then create a Dog subclass and override the speak() method to print out a more specific dog barking sound.

class Animal {
    public function speak() {
        echo "Generic animal sound.";
    }
}

class Dog extends Animal {
    public function speak() {
        echo "Woof!";
    }
}

$animal = new Animal();
$animal->speak(); // 输出: "Generic animal sound."

$dog = new Dog();
$dog->speak(); // 输出: "Woof!"

Note:

  • The signature (name, parameters, return value type) of the overridden method must be exactly the same as the original method in the parent class.
  • If the method of the subclass is annotated with @override, it may improve the readability and maintainability of the code. The
  • parent:: syntax can be used to access the original implementation of a parent class in an overridden method.

The above is the detailed content of How to override functions in PHP?. 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