php callback function example

php callback function example

php callback function example


資料來源: Gemini


01.

function greet($name) {
  echo "Hello, $name!" . PHP_EOL;
}

function callSomeone($name, $callback) {
  echo "Calling $name..." . PHP_EOL;
  $callback($name);
}

callSomeone("Alice", "greet");


02.

$callback = function($name) {
  echo "Hi, $name!" . PHP_EOL;
};

callSomeone("Bob", $callback);


03.

$numbers = [1, 2, 3, 4];

function double($num) {
  return $num * 2;
}

$new_numbers = array_map("double", $numbers);

print_r($new_numbers); // Output: Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 )


04.

class Math {
  public function square($num) {
    return $num * $num;
  }
}

$math = new Math;

$numbers = [2, 3, 4];
$squares = array_map([$math, "square"], $numbers);

print_r($squares); // Output: Array ( [0] => 4 [1] => 9 [2] => 16 )

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *