4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPで、無名関数を変数代入せずにカッコの後ろにカッコを付けて呼び出しするやつ

Posted at

**IIFE(Immediately Invoked Function Expression; 即時実行関数式)**と呼ぶそうです。

概要

こういう事がしたい

index.php
<?php
function getSum($first) {
  return function ($second) use ($first) {
    return $first + $second;
  };
}

// こうじゃなくて
$func = getSum(1);
echo $func(2); //-> 3

// こうしたい
echo getSum(1)(2); //-> 3

環境

  • Windows 10 Pro 1803 Windows Subsystem for Linux / Ubuntu 16.04.4 LTS
  • Docker version 17.12.0-ce, build c97c6d6

確認

下記コードで、各バージョンのPHPで確認

$ docker run -it --rm --name my-php-test-53 -v `wslpath -w $PWD`:/usr/src/myapp -w /usr/src/myapp php:5.3-cli php index.php
$ docker run -it --rm --name my-php-test-56 -v `wslpath -w $PWD`:/usr/src/myapp -w /usr/src/myapp php:5.6-cli php index.php
$ docker run -it --rm --name my-php-test-70 -v `wslpath -w $PWD`:/usr/src/myapp -w /usr/src/myapp php:7.0-cli php index.php
$ docker run -it --rm --name my-php-test-72 -v `wslpath -w $PWD`:/usr/src/myapp -w /usr/src/myapp php:7.2-cli php index.php

結果

PHP 結果
5.3 Parse error: syntax error, unexpected '(', expecting ',' or ';'
5.6 Parse error: syntax error, unexpected '(', expecting ',' or ';'
7.0 成功
7.2 成功

どうやらPHP7.0+でできるようになったそうです。

PHP 7.0.x へのマイグレーションガイドには明記されていないようなのですが、できるようです。

参考

4
1
1

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
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?