Home >Backend Development >PHP Tutorial >How to express the two suffix parameters in php

How to express the two suffix parameters in php

下次还敢
下次还敢Original
2024-04-27 11:06:29668browse

In PHP functions, there are two special parameters: variable number of parameters...$var and callback function callable $callback. A variable number of arguments allows a function to receive any number of arguments, stored as an array. Callback functions allow a function to accept a function and execute it under specific conditions.

How to express the two suffix parameters in php

Two parameters after the PHP function

In the PHP function, there are two special parameters: ...$var and callable $callback. They allow functions to receive a variable number of arguments and callback functions.

Variable number of parameters:...$var

  • Syntax: function functionName(...$var)
  • Purpose: Allow the function to accept any number of parameters and store them in the $var variable in the form of an array.
  • For example:
<code class="php">function sum(...$numbers) {
  $total = 0;
  foreach ($numbers as $number) {
    $total += $number;
  }
  return $total;
}

echo sum(1, 2, 3, 4, 5); // 输出: 15</code>

Callback function: callable $callback

  • Syntax: function functionName(callable $callback )
  • Purpose: Allows a function to accept a callback function and execute it under specific conditions.
  • For example:
<code class="php">function filterArray(array $array, callable $callback) {
  $filteredArray = [];
  foreach ($array as $element) {
    if ($callback($element)) {
      $filteredArray[] = $element;
    }
  }
  return $filteredArray;
}

$callback = function ($value) {
  return $value > 10;
};

$filteredArray = filterArray([1, 2, 10, 15, 20], $callback); // 输出: [15, 20]</code>

Note:

  • The variable number of parameters must be the last parameter in the function parameter list.
  • Callback functions can be represented by anonymous functions or function names.

The above is the detailed content of How to express the two suffix parameters 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