0
0

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 Manual 読書会(9回目)(関数)

Posted at

PHPに慣れる為に週1ぐらいで更新していきます。PHP Manualを読んで実験して行きます。

前回:PHP Manual 読書会(8回目)(制御構造2)

可変関数

PHP は可変関数(variable functions)の概念をサポートします。 これにより、変数名の後に括弧が付いている場合、その値が何であろうと PHPは、同名の関数を探し実行を試みます。 この機能は、コールバック、関数テーブル等を実装するために使用可能です。

変数名の後ろに括弧がついていると同名の関数を探しにいくそうです。

<?php

function hoge() {
    echo "hello\n";
}

$name = 'hoge';

$name();
hello

無名関数

無名関数はクロージャとも呼ばれ、 関数名を指定せずに関数を作成できるようにするものです。 コールバック パラメータとして使う際に便利ですが、用途はそれにとどまりません。
無名関数の実装には Closure クラスを使っています。

<?php

function run($callback) {
    echo get_class($callback) . "\n";
    $callback(1);
}

run(function($num){
    echo "$num\n";
});
Closure
1

get_classを使うとClosureがとれました。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?