CodeIgniter Forums
$function() ? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forum-20.html)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forum-23.html)
+--- Thread: $function() ? (/thread-11242.html)



$function() ? - El Forum - 09-01-2008

[eluser]Boyz26[/eluser]
Hi everyone,

Is there any way I can convert a string variable to a function?
I am storing a series of actions in the database that will be called later.

Code:
function recipe($id) {
$this->db->where('recipe_id', $id);
$query = $this->db->get('actions');
foreach($query->result() as $row):
//my question: can I do any of these?
  $actionName = $row->actionName;
  $this->$actionName();
//or..
  convertToFunction($actionName);
//or..
  if($actionName == 'fryAnEgg') { $this->fryAnEgg() }
  elseif($actionName== 'bakeCookie') { $this->bakeCookie() }
//and so on..
endforeach;
}

function fryAnEgg() {
  //complex function
}

function bakeCookie() {
//another function
}

I will be having many many actions, so I don't want to make a long elseif list..

Thank you!!


$function() ? - El Forum - 09-01-2008

[eluser]Colin Williams[/eluser]
You can $this->$method or call_user_func(array($this, $method)), but it's a good idea to run a function_exists or method_exists test before you call it. For security reasons, you might also want to use an array to store valid methods.


$function() ? - El Forum - 09-01-2008

[eluser]Boyz26[/eluser]
Thank you!

For $this->$method, does $method need to be 'method()' or just 'method'?

Would you mind explaining more about security with using an array to store valid methods?


$function() ? - El Forum - 09-01-2008

[eluser]Colin Williams[/eluser]
It needs to be like 'method' and you actually do $this->$method(). Sorry I wasn't clear about that.

Here's an example of securing methods that can be called with an array.

Code:
class Example extends Model {

  var $allowed_actions;
  
  function Example()
  {
    $this->allowed_actions = array('bake', 'frost', 'eat');
  }

  function recipe()
  {
    // Get the recipe action somehow and store it in $action...
    if (in_array($action, $this->allowed_actions) and method_exists($this, $action))
    {
      $this->$action();
    }
    else
    {
      show_error('Action does not exist or is not allowed');
    }
  }

  function bake()
  {

  }

  [...]

}



$function() ? - El Forum - 09-01-2008

[eluser]Boyz26[/eluser]
Thank you so much! You are of much help!