2

我将 Propel 与 CodeIgniter 一起使用。我创建了一个MY_Model类(extends CI_Model),它使用它的构造函数来加载 Propel。

如果你好奇:

class MY_Model extends CI_Model{
    public function __construct(){
        parent::__construct();

        require_once '/propel/runtime/lib/Propel.php';
        Propel::init('/build/conf/project-conf.php');
        set_include_path('/build/classes'.PATH_SEPARATOR.get_include_path());
    }
}

所以,现在当我创建一个新的 CodeIgniter 模型时,它会为我加载 Propel。问题是,我为一些 Propel 生成的模型添加了命名空间。我想我可以use Reports;在模型的构造函数中添加这条线,但是不行。

class Reports_model extends MY_Model{
    function __construct(){
        parent::__construct();
        use Reports;
    }
}

这给了我

语法错误,意外的 T_USE

好吧,我想,让我们试着把它放在构造函数之外:

class Reports_model extends MY_Model{
    use Reports;

    function __construct(){
        parent::__construct();
    }
}

现在我得到一个更长的错误:

语法错误,意外的 T_USE,需要 T_FUNCTION

作为最后的手段,我use Reports;在类声明之前添加了:

use Reports;

class Reports_model extends MY_Model{
    function __construct(){
        parent::__construct();
    }
}

现在我得到更多的错误!

非复合名称“报告”的使用语句无效
未找到类“报告查询”

在课堂上的另一个函数中,我有一行$report = ReportsQuery::create();.

那么,我怎样才能让use Reports;线路正常工作呢?我真的不想Reports\ 到处添加。

我该怎么做才能做到:

$report = ReportsQuery::create();

代替:

$report = Reports\ReportsQuery::create();
4

2 回答 2

2

显然,use关键字并没有像我那样做。这只是告诉 PHP 在哪里寻找一个类。

我需要做的是使用namespace关键字来声明我的类在Reports命名空间中。然后我不得不告诉它MY_Model从全局命名空间中使用。

namespace Reports;
use MY_Model;

class Reports_model extends MY_Model{
    function __construct(){
        parent::__construct();
    }
}

我也可以class Reports_model extends \MY_Model{代替这use MY_Model;条线。

现在的问题是 CodeIgniter 无法找到Reports_model,因为它现在位于Reports命名空间内,而不是全局命名空间内。我在另一个 StackOverflow 问题( https://stackoverflow.com/a/14008411/206403)中找到了解决方案。

有一个函数叫做class_alias这基本上是魔法。

namespace Reports;
use MY_Model;

class_alias('Reports\Reports_model', 'Reports_model', FALSE);

class Reports_model extends MY_Model{
    function __construct(){
        parent::__construct();
    }
}

而且效果很好!

于 2013-05-29T15:31:55.727 回答
0

只需在具有命名空间的代码中为所有没有命名空间的类添加“\”前缀

于 2013-05-29T14:59:31.350 回答