父类的数据数组未到达View

时间:2012-07-15 05:17:12

标签: php codeigniter

我的观点期望某些变量由调用它们的控制器定义。因此,我创建了自己的控制器来扩展。反过来,该控制器扩展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;
}

}

因此,例如,我可以为普通页面定义一个Controller,如下所示

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抱怨我有变量未定义?

1 个答案:

答案 0 :(得分: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);
    }
}