我将 Propel 与 CodeIgniter 一起使用。我创建了一个 MY_Model
类(它扩展了 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;
}
}
这给了我
syntax error, unexpected T_USE
好吧,我想,让我们尝试将它放在构造函数之外:
class Reports_model extends MY_Model{
use Reports;
function __construct(){
parent::__construct();
}
}
现在我收到一个更长的错误:
syntax error, unexpected T_USE, expecting T_FUNCTION
作为最后的手段,我在类声明之前添加了 use Reports;
:
use Reports;
class Reports_model extends MY_Model{
function __construct(){
parent::__construct();
}
}
现在我收到更多错误!
The use statement with non-compound name 'Reports' has no effect
Class 'ReportsQuery' not found
在类中的另一个函数中,我有一行执行 $report = ReportsQuery::create();
。
那么,如何才能使 use Reports;
行正常工作呢?我真的不想在任何地方添加Reports\
。
我怎样才能做到这样:
$report = ReportsQuery::create();
而不是:
$report = Reports\ReportsQuery::create();
最佳答案
显然,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();
}
}
效果非常好!
关于php - 在扩展类中使用命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16817117/