我有两个变量:
$a = 'some_class';
$b = 'some_method';
我想做的是这样的(方法是静态的):
$a::$b;
可能吗?我试过反射类,但我不能调用静态方法......
我有两个变量:
$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 个选项本身作为一个函数并从它们自己进行调用。
在实践中差别不大,但在优化这样的过程时可能有意义。
您必须将 () 添加到 var 的末尾才能将其转换为方法。$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!