これを行うには複数のオプションがあります
- クラス名とメソッド名に文字列変数を使用する
- call_user_func() と一緒にコールバックを使用する
- リフレクションの使用
次の例は、これらのオプションを示しています。
<?php
namespace vendor\foo;
class Bar {
public static function foo($arg) {
return 'foo ' . $arg;
}
}
オプション 1 : クラス名とメソッド名に文字列変数を使用する:
/* prepare class name and method name as string */
$class = '\vendor\foo\Bar';
$method = 'foo';
// call the method
echo $class::$method('test'), PHP_EOL;
// output : foo test
オプション 2: コールバック変数を Perpare して、次の場所に渡しますcall_user_func()
。
/* use a callback to call the method */
$method = array (
'\vendor\foo\Bar', // using a classname (string) will tell call_user_func()
// to call the method statically
'foo'
);
// call the method with call_user_func()
echo call_user_func($method, 'test'), PHP_EOL;
// output : foo test
オプション 3: ReflectionMethod::invoke() を使用します。
/* using reflection to call the method */
$method = new \ReflectionMethod('\vendor\foo\Bar', 'foo');
// Note `NULL` as the first param to `ReflectionMethod::invoke` for a static call.
echo $method->invoke(NULL, 'test'), PHP_EOL;
// output : foo test