Welcome Guest, Not a member yet? Register   Sign In
$function() ?
#1

[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!!
#2

[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.
#3

[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?
#4

[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()
  {

  }

  [...]

}
#5

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




Theme © iAndrew 2016 - Forum software by © MyBB