2

Consider the class abc

class abc{
  public function xyz(){
     /*Some processing here*/
     return true;
  }
};

Suppose I don't know the name of the method directly, but have its name stored in variable, then how can I call the method?

2 Answers2

3
<?php
class abc{
  public function xyz(){
     /*Some processing here*/
     return true;
  }
};

$method='xyz';  // Define your method name from database
$a= new abc();
$a->$method(); // call method
?>

Would you please refer above code ?

Anyone
  • 2,814
  • 1
  • 22
  • 27
Maulik Kanani
  • 642
  • 6
  • 22
  • Ideally you also first check whether the method really exists via [method_exists($a, $method)](http://php.net/manual/en/function.method-exists.php) – Philipp Jun 18 '16 at 07:50
1

You can try like below:

class abc{
  public function xyz(){
     echo "Called!";
  }
}

$obj = new abc();
$fun = "xyz";
call_user_func(array($obj, $fun));

Also answered here How to call PHP function from string stored in a Variable

Community
  • 1
  • 1