LoginSignup
0
0

More than 1 year has passed since last update.

PHP関数を変数に代入してみましょう!

Posted at

無名関数



関数を値として扱う為に変数に代入します!

以下の関数があったとします。

index.php

<?php

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



変数 $sum に上の処理を代入します。

値だけ代入したいので関数名のsumは消して、

} の後に ; をつけます。


index.php

<?php

$sum = function ($a, $b, $c) {    //関数名のsumは消します
  return $a + $b + $c;
};



ではこの変数を使ってみましょう!

変数$sumに(1, 2, 3)の引数を渡します。

index.php

$sum = function ($a, $b, $c) {
  return $a + $b + $c;
};
echo $sum(1, 2, 3) . PHP_EOL;



ターミナルに以下を実行します。

~$ php index.php



計算結果が出力されました!

~ $ php main.php
6
~ $ 



無名関数は、他の関数の引数として使う事もできます ☆

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0