Welcome Guest, Not a member yet? Register   Sign In
Variable Scope - Class Wide Variable
#1

[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
#2

[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;
}
}
?>
#3

[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
#4

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




Theme © iAndrew 2016 - Forum software by © MyBB