动态调用类

时间:2014-07-21 21:29:02

标签: php class dynamic

class App 
{
    public function __construct()
    {
        echo "app is now running...\n";
        $this->getModel('Something');
    }

    public function getModel($name)
    {
        return new $this->getModelInstance($name);
    }

    protected function getModelInstance($name)
    {
        return 'Model_' . $name;
    }
}

我有自动加载器设置和工作。为什么我不能以这种方式加载Model_Something,但我收到以下错误:

Notice: Undefined property: App::$getModelInstance in C:\Apache24\htdocs\ProjectName\app\App.php on line 13

Fatal error: Class name must be a valid object or a string in C:\Apache24\htdocs\ProjectName\app\App.php on line 13

1 个答案:

答案 0 :(得分:2)

试试这个:

public function getModel($name) {
  $modelInstanceName = $this->getModelInstance($name);
  return new $modelInstanceName();
}


---
实例化类的正确方法是:

new Classname($parameter);

所以当你这样做时:

new $this->getModelInstance($name);

班级名称是:

$this->getModelInstance

所以它在你的App类中寻找getModelInstance属性(而不是函数),这是不存在的。