Calling function from its name in a PHP class [duplicate]

6

I'm creating an application where I need to call the function based on its name inside the class. the intention of using it this way is that I can call these functions through ajax and the server will understand without having to do a switch or something like that. Basically what I have is this

class MinhaClasse {
    var foo = 'ola mundo';
    var bar = 'teste para o stack';
    public function index($fn = 'a')
    {
        $result = $this->$fn(); // <-- é isso que eu quero
    }
    private function a()
    {
        return $this->foo;
    }
    private function b()
    {
        return $this->bar;
    }
}

Basically, I need from a string or some element that I send to the function index($fn) it executes a function inside my class. Would anyone have some way to do this?

EDIT : Today, in order to get there, I'm forced to make a switch, which pollutes the code and still forces me to edit if there are changes, as in the example below: p>

class MinhaClasse { //com switch tosco...
    var foo = 'ola mundo';
    var bar = 'teste para o stack';
    public function index($fn = 'a')
    {
        switch($fn){
            case 'b': 
               $result = $this->b();
            break;
            default : 
               $result = $this->a();
            break;
        };

        echo $result;
    }
    private function a()
    {
        return $this->foo;
    }
    private function b()
    {
        return $this->bar;
    }
}
    
asked by anonymous 21.12.2015 / 19:46

2 answers

6

You can call the function using {}

It would look like this:

class MinhaClasse {
    var foo = 'ola mundo';
    var bar = 'teste para o stack';
    public function index($fn = 'a')
    {
        $result = $this->{$fn}(); // <-- é isso que eu quero
    }
    private function a()
    {
        return $this->foo;
    }
    private function b()
    {
        return $this->bar;
    }
}
    
21.12.2015 / 19:52
5

You can do this:

class MinhaClasse {
    var $foo = 'ola mundo';
    var $bar = 'teste para o stack';
    public function index($fn = a)
    {
        $result = $this->$fn(); // <-- é isso que eu quero
    }
    private function a()
    {
        return $this->foo;
    }
    private function b()
    {
        return $this->bar;
    }
}
$classe = new MinhaClasse();
$classe->index();
$classe->index(b);

See running on ideone .

I prefer this form by not using strings , you pass the function's own symbol.

    
21.12.2015 / 19:56