按字符串实例化类

时间:2013-07-28 14:00:45

标签: php

我有这段代码。

    $contrl = stripslashes($this->params['controller'].'Controller'); //PostController
    $obj = new $contrl(); // What's won't work
    //this don't work too
    $contrl = 'PostController';
    $obj = new $contrl();
    //but this work good
    $obj = new PostController();

我不明白为什么会发生这种情况以及如何解决它?

1 个答案:

答案 0 :(得分:0)

我还没有对它进行过测试,但我很确定应该这样做(as per the doc):

$obj = new $contrl;