Help us understand the problem. What is going on with this article?

PHPの文字列と配列は実行可能?!?!

文字列は実行可能!!!

function example_func() {
  echo 'example_func was called';
}

'example_func'();
// example_func was called

配列も実行可能!!!

class ExampleClass
{
    public static function example()
    {
        echo 'ExampleClass::example was called';
    }
}

['ExampleClass', 'example']();
// ExampleClass::example was called

なにこれ!!!

どちらもコールバック / Callableでタイプヒンティングされた引数に渡せる形式。

callableis_callable関数でtrueと評価されるような、呼び出し可能な引数を定義する際に使います

function call_callback(callable $callback) {
    $callback();
}

// callableでタイプヒンティングされた引数に渡せる形式は3つあります

function example_func() {
  echo 'example_func was called';
}

class ExampleClass
{
    public static function example1()
    {
        echo 'ExampleClass::example1 was called';
    }

    public function example2()
    {
        echo 'ExampleClass::example2 was called';
    }

    public function __invoke()
    {
        echo 'ExampleClass was called';
    }
}

// 1.文字列
// 関数名
call_callback('example_func');
// example_func was called

// 静的メソッド
call_callback('ExampleClass::example1');
// ExampleClass::example1 was called


// 2.配列
// メソッド
call_callback([new ExampleClass, 'example2']);
// ExampleClass::example2 was called

// 静的メソッド
call_callback(['ExampleClass', 'example2']);
// ExampleClass::example1 was called


// 3.__invokeマジックメソッドを実装したオブジェクト
// オブジェクト
call_callback(new ExampleClass);
// ExampleClass was called

// 無名関数
call_callback(function () {
    echo 'closure was called';
});
// closure was called

うーん

callable引数に渡すとき以外使い場所はない
ましてや文字列や配列を直接呼び出すことはないですね

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away