views:

162

answers:

3

They say that eval() is evil. I want to avoid the use of the eval() line using proper PHP5 functionality. Given a class name in a static class method, how do I make it return a real object?

class Model {
  public static function loadModel($sModelPath) {
    if (!(strpos(' ' . $sModelPath, '/')>0)) {
      $sModelPath .= '/' . $sModelPath;
    }
    $sModelName = str_replace('/','_',$sModelPath);
    // P is a global var for physical path of the website
    require_once(P . '_models/' . $sModelPath . '.php');
    eval("\$oObject = new $sModelName" . '();');
    return $oObject;
  }
}
+10  A: 

return new $sModelName();

You can call functions by a dynamic name as well:

$func = "foobar";
$func("baz"); //foobar("baz")
Kenaniah
+3  A: 

Yep, Kenaniah beat me to it. Gotta type faster...

More info here: http://php.net/manual/en/language.oop5.php, see the first user note.

Per Wiklander
A: 

Try:

$m = new Model();
$m = $m->makeModel();

class Model {
  public static function loadModel($sModelPath) {
    if (!(strpos(' ' . $sModelPath, '/')>0)) {
      $sModelPath .= '/' . $sModelPath;
    }
    $sModelName = str_replace('/','_',$sModelPath);
    // P is a global var for physical path of the website
    require_once(P . '_models/' . $sModelPath . '.php');
    function makeModel(){
      $model = new $sModelName;
      return  $model;
    }
  }

}
Moshe
Just a note: you don't have to store your object in a variable before returning it. Either way, it's functionally equivalent.
Kenaniah