[eluser]dmol[/eluser]
Hi all,
I'm new to CI and indeed PHP classes and I'm having trouble with scope of variables.
I want to define a variable that can be used throughout a controller. It should be straightforward but the solutions I've seen don't seem to work for me.
I'm using CI version 2 and PHP version 5.1.6
<?php
Below are two basic versions of the controller:
This does not work:
Code:
class Main extends CI_Controller {
var $data; //I've also tried 'private $data' without success
function Main()
{
parent::__construct();
}
function index()
{ $this->data['name'] = "hello"; }
function other()
{
echo $this->data['name']; //fails. ['name'] is empty
}
}
In the following version, the variable is visible in other functions but I think it's structure is causing problems when redirecting. I also don't know why an empty index function needs to be defined.
Code:
class Main extends CI_Controller {
var $data;
function Main()
{
parent::__construct();
$this->data['name'] = "hello";
}
function other()
{
echo $this->data['name']; //works. ['name'] contains hello
}
function index() //needs to be defined for some reason
{
}
}