CodeIgniter Forums
Variable Scope - Class Wide Variable - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forum-20.html)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forum-23.html)
+--- Thread: Variable Scope - Class Wide Variable (/thread-23193.html)



Variable Scope - Class Wide Variable - El Forum - 10-03-2009

[eluser]Unknown[/eluser]
Hi,

My controller currently has 6 functions (may be more later), and each function creates a variable called $data['categories']. This variable contains the same data each time, so my question is can I set the $data['categories'] variable at the class (controller) level once, and then access it in any of the controller's methods.


Controller Code:
Code:
$data['categories'] = $this->MCategory->getAllCategories();
//this line appears in all functions. How can I create this variable in the controller so
//that it's available throughout all of the controller's functions (and passed to the view
//with $this->load->vars($data)

...      
$this->load->vars($data);
$this->load->view('v_flavour_template');

Many thanks


Variable Scope - Class Wide Variable - El Forum - 10-03-2009

[eluser]Yorick Peterse[/eluser]
Code:
<?php
class Some_controller extends Controller
{
private $data;

function __construct()
{
$this->$data['categories'] = $this->MCategory->getAllCategories();
}

function index()
{
// do something with $this->data;
}
}
?>



Variable Scope - Class Wide Variable - El Forum - 10-03-2009

[eluser]Unknown[/eluser]
Thanks Yorick,

Had a play with your suggestion, but got an error when using private $data;, but not when using var $data;

Looked into it, and realised it's because my server's running PHP4.

Also, putting the code in the __construct() function didn't work, but again figured that was a PHP5 thing.

Converted to PHP4 and it works a treat.

Categories Controller Code:

Code:
class Categories extends Controller {

var $data;

function Categories()
    {
        parent::Controller();
        $this->data['categories'] = $this->MCategories->getAllCategories();
    }


function index()
    {
        $this->data['content'] = "v_homepage";
        $this->data['title'] = "Product Categories";
        $this->data['homeProducts'] = $this->MProducts->getRandomProducts(6);
        
        $this->load->view('v_template',$this->data);
    }

}

Many thanks


Variable Scope - Class Wide Variable - El Forum - 10-03-2009

[eluser]Yorick Peterse[/eluser]
No problem Smile