6
I am creating an application where I need to call the function based on its name within the class. the intention to use this way is that I can call these functions through ajax and the server will understand without it being necessary to make 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 that from a string or some element I send to the function index($fn)
it performs a function within my class. Someone would have some way to do this?
EDIT: Today, in order to achieve this, I am obliged to make a switch, which pollutes the code and still requires me to keep editing if there are changes, as in the example below:
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;
}
}
that’s right, solved my problem!
– LeandroLuk
I liked the
{$fn}
. It is a little known syntax, but it helps to avoid different interpretations especially now with the changes in PHP 7.– utluiz