My Views expect certain variables to be defined by the controllers invoking them. As such, I created my own controller to extend from. This controller, in turn, extends 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;
}
}
So, for instance, I may define a Controller for a plain page as follows
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);
}
}
Then, in mainview.php, I have the following bit of code:
<?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>"';
}
?>
But I get the following errors:
Message: Undefined variable: {stylesheets|scripts}
Message: Invalid argument supplied for foreach()
Isn’t it that when parent::__construct() gets called, the $data_bundle array should’ve been initialized? Why is CI/PHP complaining that I have variables undefined?
You missed
selfin parent class constructor when initializing the static property.But You don’t need to use static property in this case, controller should have only one instance, so a instance property is enough.