我的视图期望某些变量由调用它们的控制器定义。因此,我创建了自己的控制器来扩展。反过来,这个控制器扩展了CI_Controller
.
class MainController extends CI_Controller{
static protected $data_bundle;
/**
All classes that will extend MainController should have their own constructors
calling the constructor of MainController.
*/
public function __construct(){
parent::__construct();
$data_bundle["title"] = "";
$data_bundle["content"] = "";
$data_bundle["stylesheets"] = array();
$data_bundle["scripts"] = array();
$data_bundle["echo_content"] = true;
}
}
因此,例如,我可以为普通页面定义一个控制器,如下所示
class PlainPage extends MainController{
public function __construct(){
parent::__construct()
}
public function page(){
parent::$data_bundle["title"] = "Plain Page"
parent::$data_bundle["content"] = "The quick brown fox jumps over the lazy dog."
$this->load->view("mainview", parent::$data_bundle);
}
}
然后,在 中mainview.php
,我有以下代码:
<?php
foreach($stylesheets as $style){
echo '<link rel="stylesheet" type="text/css" href="css/$style" />"';
}
?>
<?php
foreach($scripts as $script){
echo '<script type="text/javascript" src="scripts/$script"></script>"';
}
?>
但我收到以下错误:
Message: Undefined variable: {stylesheets|scripts}
Message: Invalid argument supplied for foreach()
不是说当parent::__construct()
被调用时,$data_bundle
数组应该已经初始化了吗?为什么 CI/PHP 抱怨我有未定义的变量?