0

我的视图期望某些变量由调用它们的控制器定义。因此,我创建了自己的控制器来扩展。反过来,这个控制器扩展了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 抱怨我有未定义的变量?

4

1 回答 1

1

初始化静态属性时,您错过self了父类构造函数。

public function __construct(){
    parent::__construct();
    self::$data_bundle["title"] = "";
    self::$data_bundle["content"] = "";
    self::$data_bundle["stylesheets"] = array();
    self::$data_bundle["scripts"] = array();
    self::$data_bundle["echo_content"] = true;
}

但是在这种情况下你不需要使用静态属性,控制器应该只有一个实例,所以一个实例属性就足够了。

class MainController extends CI_Controller{

protected $data_bundle = array();

/**
All classes that will extend MainController should have their own constructors
calling the constructor of MainController.
*/
public function __construct(){
    parent::__construct();
    $this->data_bundle["title"] = "";
    $this->data_bundle["content"] = "";
    $this->data_bundle["stylesheets"] = array();
    $this->data_bundle["scripts"] = array();
    $this->data_bundle["echo_content"] = true;
}

}

class PlainPage extends MainController{
    public function __construct(){
        parent::__construct()
    }

    public function page(){
        $this->data_bundle["title"] = "Plain Page"
        $this->data_bundle["content"] = "The quick brown fox jumps over the lazy dog."
        $this->load->view("mainview", $this->data_bundle);
    }
}
于 2012-07-15T05:52:07.443 回答