Global array seems to be losing object's data members

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
bob1234
Forum Newbie
Posts: 5
Joined: Fri Oct 31, 2008 3:48 pm

Global array seems to be losing object's data members

Post by bob1234 »

Hello,

I am making a class scheduler. I have an object that represents courses. If these courses can go together in a way that match some criteria defined by the user, we have a schedule object. Schedule objects are really just a 2-d array, with an array for each day. I have a global array that holds all the schedules found for certain criteria so far.

For clarity:

Code: Select all

 
<?php
class Course
{
$name;
$course_id;
$prof;
...etc.
}
 
class Schedule
{
 public $schedule = array("monday"=>array(), "tuesday"=>array(), "wednesday"=>array(), "thursday"=>array(), "friday"=>array(), "saturday"=>array()); 
}
 
?>
 
Each of the arrays named after a day in the Schedule class hold a bunch of Course objects, the courses that are on that day.

Here is my problem:

I defined the global array and called the function that populates it with schedules. Its a recursive function that adds valid schedules onto the global schedule array. Every time the function adds a schedule, I print the array and it prints fine; each schedule's array has one or more course objects. Each iteration adds a (populated) schedule object to that global array properly.

Here is the strange part. When the function returns, the global array should now hold all the schedule objects found by the function. When I print that global array of schedules after I called the function, it still holds the same number of schedule objects, so that is fine, but the problem is they are all now empty. I have no clue why this is happening.

To clarify:

Code: Select all

 
global $schedulearray;
$schedulearray = array();
define("MAX", 10);
 
 
makeSchedule();
 
var_dump($schedulearray); //DEBUG #1
 
function makeSchedule()
{
        global $schedulearray;
    $schedulecount = 0;
    while($schedulecount<MAX)
    {
        $s = new Schedule();
        $s->getCourses();
        $schedulearray[] = $s;
        $schedulecount++;
    }
 
    var_dump($schedulearray);  //DEBUG #2
 
}
 
I left the logic of getCourses() out because its too many lines. The statement labeled DEBUG #2 will print first and will print 10 schedule objects, each populated with courses. DEBUG #1 will also print 10 schedule objects, but the day entries are now empty. To clarify, the 2-d array still holds a Monday array, a Tuesday array ..etc , but those arrays are now empty when they weren't right before the function terminated

I have been looking for an answer for hours so far, but have found none.
Post Reply