I’m trying to access an array declared in a class from a function within the same class. I’ve attempted a couple different ways to try to make it work but I’m relatively new to PHP. This is a snippet of my code
class Site extends CI_Controller {
var $dates = array(
"Task" => NULL,
"Date1" => NULL,
"Date2" => NULL,
"TimeDiff" => NULL
);
function index()
{
if($this->$dates['Date1'] != NULL && $this->$dates['Date2'] != NULL)
{
$this->$dates['TimeDiff'] = $this->$dates['Date2']->getTimestamp() - $this->$dates['Date1']->getTimestamp();
}
$this->load->view('usability_test', $this->$dates);
}
I also attempted using the global keyword as such
global $dates;
And I still receive a “Undefined variable” error regardless. Thanks!
You want
$this->dates['Date1']instead of$this->$dates['Date1']. Notice the absence of the$beforedates.As a side note, be sure you’re properly extending
CI_Controllerby defining the__construct()like this:Another thing to note,
varis deprecated as of PHP5. You’ll want to use eitherpublic,private, orprotecteddepending on your needs (Edit: assuming, of course, that you are using PHP5).