Home > Backend Development > PHP Problem > What is the effect of adding... in front of the parameters of the php calling method?

What is the effect of adding... in front of the parameters of the php calling method?

尊渡假赌尊渡假赌尊渡假赌
Release: 2023-06-20 14:13:01
Original
1741 people have browsed it

Add... in front of the php calling method parameters to set the specified function parameters to unlimited number of parameters. When the function declaration requires multiple actual parameters but we actually don’t know how many to pass in. Or when the quantity passed in is variable, it is used at this time.

What is the effect of adding... in front of the parameters of the php calling method?

Operating system for this tutorial: Windows 10 system, php8.1.3 version, Dell G3 computer.

In PHP, you can use the `...` syntax called a variable-length parameter list or "splat" (splash symbol) to set the specified function parameters to an unlimited number of parameters. . This is used when the function declaration requires multiple actual parameters but we actually don’t know how many to pass in or the number passed in is variable.

When calling a function, add `...` after the function name to split the array into independent parameters for processing. The argument list can also be obtained through the `func_get_args()` function.

以下示例演示如何在 PHP 中使用 `...` 参数:
```php
function sum(...$numbers) {
   $total = 0;
   foreach ($numbers as $number) {
       $total += $number;
   }
   return $total;
}
echo sum(1, 2, 3); // 输出 6
echo sum(1, 2, 3, 4, 5); // 输出 15
```
Copy after login

In this example, the parameter `$numbers` is set to a variable length parameter list. Use a `foreach` to loop through each parameter and add them together.

The above is the detailed content of What is the effect of adding... in front of the parameters of the php calling method?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template