Execute functions inside variables in PHP

3

In a certain project I'm having an error trying to create a variable as a function, for example:

namespace Classes;

class Teste
{
    public static function abc() { return 'teste'; }
}

Calling the function usually works:

\Classes\Teste::abc();

But when I try:

   $class = "\Classes\Teste::abc";
   $class();

It returns an error:

Fatal error: Call to undefined function \Classes\Teste::abc() 
    
asked by anonymous 03.02.2015 / 03:52

1 answer

5

The error in the second line because you try to call a string (return of abc() ) as a function. If you just call the method you can use call_user_func function, the first argument being the / method and the second its arguments. To call methods with more arguments use call_user_func_array

 <?php
class Teste
{
    public static function abc() {
        return 'teste';
    }

    public static function soma($a, $b){
        return $a+$b;
    }

}

$class = "Teste::abc";
echo call_user_func($class) .'<br>';

$str_metodo = "Teste::soma";
echo call_user_func_array($str_metodo, array(30,1));

phpfiddle - example

    
03.02.2015 / 04:02