Run functions within variables in PHP

Asked

Viewed 671 times

3

In a certain project I am in error when 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() 
  • The goal is just to invoke the method? or has something else?

  • I need to execute the function being that the class name is generated dynamically.

1 answer

6


The error of in the second line because you try to call a string(return from abc()) as a function. If you are only calling the method you can use function call_user_func, being the first argument the function/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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.