I am pretty rusty on php, and am just learning how to use classes, and now something wierd is happening, which may just be how php works – I am not sure.
I have an array which is static to a class (Project), and what I want to do is fill the array as soon as the page is loaded (in index.php), and then use projects from it from it when populating data. But I also want to use the SAME project array in other php files (such as my ajax_show_timesheet.php).
When I try to access the array from another php file:
Project::$projectArray[key];
The array is empty. If I call
Project::createProjects();
again from within the other php file, it repopulates.
So why can’t I access the same static array from within various .php files?
Here is what I am doing:
CLASS PROJECT:
class Project
{
public static $projectArray;
public $projectID;
public function __construct($projID=0){
$this->projectID = $projID;
}
public static function createProjects(){
$projectResult = mysql_query("SELECT * FROM $tblProjects");
$numRows = mysql_numrows($projectResult);
$i = 0;
while($i < $numRows){
//for each project in the DB, add one to the array
Project::$projectArray[mysql_result($projectResult, $i, "projectID")]
= new Project(mysql_result($projectResult, $i, "projectID"));
$i++;
}
}
}
In index.php I fill initialize Project:
Project::createProjects();
In ajax_show_timesheet.php I do something like:
echo Project::$projectArray[key]->projectID
and I just get back nothing.
Any help on how to use static variables across multiple files would be great!
What happens when you do this?
Because this suggests that you can’t initialize your static variable in the way that you are. It seems like you’re trying to use Project like a singleton, but that is not how a php singleton works.