PHP supports function overloading, allowing multiple functions to be defined with the same name, provided that the parameter lists are different. Overloading rules: the function name is the same, the function signature (parameter number, order or type) is different, the parameters must be passed by reference or value, and the return type can be different. Practical case: The calculateArea function implements square and rectangular area calculations through different signatures.
PHP does support function overloading, allowing you to define multiple functions with the same name, provided that they The signature (parameter list) is different.
The rules for PHP function overloading are as follows:
The following example shows the practical application of function overloading:
<?php function calculateArea($width, $height = null) { if ($height === null) { // 正方形 return $width * $width; } else { // 矩形 return $width * $height; } } echo calculateArea(5); // 输出:25(正方形) echo calculateArea(5, 10); // 输出:50(矩形)
Here, the calculateArea
function has two different Signature:
calculateArea(int $width)
: Used to calculate the area of a squarecalculateArea(int $width, int $height)
: Used to calculate the area of a rectangle The signatures of these functions are different, so they can be overloaded. Note that the $height
parameter is optional, allowing us to calculate different areas depending on the number of parameters passed in.
The above is the detailed content of Can PHP functions be overloaded? If so, what are the rules?. For more information, please follow other related articles on the PHP Chinese website!