Home  >  Article  >  Backend Development  >  Overloading and rewriting of PHP functions

Overloading and rewriting of PHP functions

WBOY
WBOYOriginal
2024-04-26 17:12:02461browse

PHP supports function overloading and rewriting to create flexible and reusable code. Function overloading: allows the creation of functions with the same name but different parameters, and calls the most appropriate function based on parameter matching. Function rewriting: Allow subclasses to define functions with the same name and override parent class methods. When subclass methods are called, they will override parent class methods.

PHP 函数的重载和重写

Function Overloading and Rewriting in PHP

PHP supports function overloading and rewriting, both techniques are available for creating flexible, reusable code.

Function overloading

Function overloading allows the creation of multiple functions with the same name but different parameters in the same scope. At run time, the function with the best matching set of parameters will be called.

function sum(int $a, int $b) {
    return $a + $b;
}

function sum(float $a, float $b) {
    return $a + $b;
}

// 调用重载的函数
echo sum(1, 2); // 输出 3
echo sum(1.5, 2.5); // 输出 4.0

Function overriding

Function overriding allows a function to be defined in a subclass with the same name as a function in the parent class. When a child class method is called, it overrides the parent class method.

class ParentClass {
    public function sayHello() {
        echo "Hello from parent class";
    }
}

class ChildClass extends ParentClass {
    public function sayHello() {
        echo "Hello from child class";
    }
}

// 创建子类对象并调用其方法
$child = new ChildClass();
$child->sayHello(); // 输出 "Hello from child class"

Practical Case

In practical applications, function overloading and rewriting can be used to create extensible frameworks, code reuse and improve readability. For example, you can use function overloading to handle different types of data, or to provide function variants with different functionality. Overriding allows a subclass to modify the behavior defined in the parent class, thereby achieving polymorphism and code maintainability.

The above is the detailed content of Overloading and rewriting of PHP functions. 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