• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
call_user_func() vs. $func_name()

#1
[eluser]neomech[/eluser]
I'm trying to wrap my head around a small issue I'm having.

I have several functions sitting in my model, and I grab the name of one of them in my code dynamically, which I store as, say, $func_name.

Now I know that call_user_func($func_name, $var) is supposed to be the preferred method over $func_name($var). However, I can't seem to call any model functions from the controller using call_user_func.

This works:
Code:
$this->Sample_model->$func_name($var);

This doesn't:
Code:
//tried this way
$this->Sample_model->call_user_func($func_name,$var);
//also tried this way
call_user_func($this->Sample_model->$func_name, $var);
I suspect I should be able to call a function in the model from my controller using call_user_func, but if so, I'm doing something wrong. Any suggestions?

#2
[eluser]ericrjones1[/eluser]
Any one please correct me if I am wrong.

I think the reason call_user_func doesn't work is because of the way Models are loaded into the framework. Models don't become globally accessible (i.e., accessible outside of the framework) once loaded, hence the need for "$this" (meaning the CI Framework) when referencing a Model.

By using $this->MY_Model->$some_method($var), you are still accessing the Model via the framework (notice "$this").

Hope this helps.

#3
[eluser]helmutbjorg[/eluser]
To call class methods you need to wrap the parameters into a single array like so:
Code:
// call_user_func(array($class, $function));
call_user_func(array($this->Sample_model->$func_name, $var));

#4
[eluser]danmontgomery[/eluser]
[quote author="helmutbjorg" date="1286874403"]To call class methods you need to wrap the parameters into a single array like so:
Code:
// call_user_func(array($class, $function));
call_user_func(array($this->Sample_model->$func_name, $var));
[/quote]

This is incorrect.

Code:
call_user_func(array($this->sample_model, $func_name), $var);

http://php.net/manual/en/function.call-user-func.php

#5
[eluser]helmutbjorg[/eluser]
Yep... you are correct. That is what I was trying to write. Should have checked it before posting...


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.