I have two variables:
$a = 'some_class';
$b = 'some_method';
What I want to do is something like this (the method is static):
$a::$b;
Is it possible? I've tried the reflection class, but I can't call static methods...
You have a few options:
<?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
Code with a backtrace so you can see what happens under the hood in 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
(
)
)
)
As you can see first way has no step in between which is being registered, it directly makes the call while the other 2 options act by themselves as a function and make the call from themselves.
In practice not a lot of difference but it might make sense when optimizing such a process.
$reflectionMethod->setAccessible(true); $reflectionMethod->invoke($obj);. The asker tagged their question with "reflection".you have to add () to the end of the var for it to turn into a method. $a::$b() not $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;
}
}
?>
Output
static return
30