Php (eval vs call_user_func vs function variables ...)

Despite the fact that I would like to check some discussions on this issue with a specific example, what would be the best approach.
Instead of using existing solutions, I created my own level of persistence (like many others). Therefore, my approach is also being questioned.

For each table in db, I have a model class that has corresponding getters and setters and some required methods. I also created only one generic DAO class that handles all types of model objects.
So, for example, to save any model object, I create a genericDAO class and a call save method that passes the model object as an attribute. The problem is that in the genericDAO runtime, the class does not know which object of the whitch model it receives and what methods (getters and setters) exist in it, so I need to call the forced method of the model class, which retrieves the list of attributes as an array of several lines.
For example, for each attribute there is an array (table_column_name, attribute_name, is_string).

When I call the save function, it looks like this:

public function save(&$VO) {  
$paramArray = $VO->getParamArray();//get array of attributes
$paramIdArray = $paramArray[0];  //first attribute is always id
/*create and execute getId() and store value into $void to check if it save or update*/
eval('$voId = $VO->get'.ucfirst($paramIdArray[1]).'();');  
...

I am currently using eval to execute these methods, but as you know, eval is very slow.
I'm going to change this to the call_user_func method.
Something like:

$voId = call_user_func(array($VO, 'get'.ucfirst($paramIdArray[1])));

But there are other solutions. I can use something like this

$method = 'get'.ucfirst($paramIdArray[1]));
$voId = $VO->$method();
or
$method = 'get'.ucfirst($paramIdArray[1]));
$voId = $VO->{$method}();

What would be the best way?

+5
source share
2 answers

First of all, there is no need to transfer links like you. You must let this read in order to try to understand how PHP handles object references.

So, it public function save(&$VO) {has to become public function save($VO) {.

-, eval ( - , ..). eval, .

-, call_user_func , PHP . call_user_func(array($obj, $method), $arg1) $obj->$foo($arg1). call_user_func_array - , .

, , :

$method = 'get' . ucfirst($paramIdArray[1]);
$voId = $VO->$method();

, method_exists, - __get ...

+8

:

$method = 'get'.ucfirst($attribute);
if(method_exists($obj, $method){
  $obj->$method();
} 

, key => value getParamArray. , ...

+2

All Articles