私には2つの変数があります:
$a = 'some_class';
$b = 'some_method';
私がやりたいのは次のようなものです(メソッドは静的です):
$a::$b;
出来ますか?リフレクションクラスを試しましたが、静的メソッドを呼び出すことができません...
私には2つの変数があります:
$a = 'some_class';
$b = 'some_method';
私がやりたいのは次のようなものです(メソッドは静的です):
$a::$b;
出来ますか?リフレクションクラスを試しましたが、静的メソッドを呼び出すことができません...
これはそれを行う必要があります
call_user_func(array($a, $b));
いくつかのオプションがあります。
<?PHP
class test {
static function doThis($arg) {
echo '<br>hello world '.$arg;
}
}
$class='test';
$method='doThis';
$arg='stack';
//just call
$class::$method($arg);
//with function
call_user_func(array($class, $method), $arg);
//ugly but possible
$command=$class.'::'.$method.'("'.$arg.'");';
eval($command);
hello world stack
hello world stack
hello world stack
PHPの内部で何が起こっているかを確認できるように、バックトレースを使用してコーディングします。
<?PHP
class test {
static function doThis($arg) {
echo 'hello world with argument: '.$arg.PHP_EOL;
print_R(debug_backtrace());
}
}
function runTest() {
$class='test';
$method='doThis';
$arg='stack';
//just call
$class::$method($arg);
//with function
call_user_func(array($class, $method), $arg);
//ugly but possible
$command=$class.'::'.$method.'("'.$arg.'");';
eval($command);
}
echo '<pre>';
runTest();
hello world with argument: stack
Array
(
[0] => Array
(
[file] => folder/test.php
[line] => 19
[function] => doThis
[class] => test
[type] => ::
[args] => Array
(
[0] => stack
)
)
[1] => Array
(
[file] => folder/test.php
[line] => 31
[function] => runTest
[args] => Array
(
)
)
)
hello world with argument: stack
Array
(
[0] => Array
(
[function] => doThis
[class] => test
[type] => ::
[args] => Array
(
[0] => stack
)
)
[1] => Array
(
[file] => folder/test.php
[line] => 22
[function] => call_user_func
[args] => Array
(
[0] => Array
(
[0] => test
[1] => doThis
)
[1] => stack
)
)
[2] => Array
(
[file] => folder/test.php
[line] => 31
[function] => runTest
[args] => Array
(
)
)
)
hello world with argument: stack
Array
(
[0] => Array
(
[file] => folder/test.php(26) : eval()d code
[line] => 1
[function] => doThis
[class] => test
[type] => ::
[args] => Array
(
[0] => stack
)
)
[1] => Array
(
[file] => folder/test.php
[line] => 26
[function] => eval
)
[2] => Array
(
[file] => folder/test.php
[line] => 31
[function] => runTest
[args] => Array
(
)
)
)
ご覧のとおり、最初の方法では登録中のステップがないため、直接呼び出しを行い、他の2つのオプションはそれ自体が関数として機能し、自分自身から呼び出しを行います。
実際には大きな違いはありませんが、そのようなプロセスを最適化する場合は理にかなっているかもしれません。
メソッドに変換するには、変数の最後に()を追加する必要があります。$ a :: $ b()ではなく$ a :: $ b;
PHP
<?php
$a = 'some_class';
$b = 'some_method';
$c = 'double';
echo $a::$b();
echo "<br>";
echo $a::$c(15);
class some_class{
public static function some_method(){
return "static return";
}
public static function double($int){
return $int*2;
}
}
?>
出力
static return
30
これはあなたのために働くでしょう:$a::$b();
例:
<?php
class A {
public static function b()
{
echo 'Done!', PHP_EOL;
}
}
$class = 'A';
$method = 'b';
$class::$method(); // Shows: Done!