开发者

PHP: How to return an instantiated class object, given a class name?

开发者 https://www.devze.com 2022-12-13 07:18 出处:网络
They say that eval() is evil. I want to avoid the use of the eval() line using proper PHP5 functionality. Given a 开发者_JAVA百科class name in a static class method, how do I make it return a real obj

They say that eval() is evil. I want to avoid the use of the eval() line using proper PHP5 functionality. Given a 开发者_JAVA百科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;
  }
}


return new $sModelName();

You can call functions by a dynamic name as well:

$func = "foobar";
$func("baz"); //foobar("baz")


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.


I know this is a 2 year old question, but I just want to point out, you all missed the question here! All your functions do not return an instantiated class, but a new class. This includes the initial function posted from the questioner!

If you want to return an instantiated class, you have to keep track of your classes and their properties in an array, and return them from there when you require an instance of the class, instead of a re-initialised class.

This method also saves a lot of processing time if your classes do a lot of processing when they are constructed. It's always better to get an instance than to create a new class, unless you really want the class-properties re-initialized. Pay attention!


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;
    }
  }

}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号