note 21106 added to ref.classobj

From: Date: Mon, 29 Apr 2002 13:48:39 +0000
Subject: note 21106 added to ref.classobj
Groups: php.notes 
Request: Send a blank email to php-notes+get-29979@lists.php.net to get a copy of this message
This is a pretty basic data structure, I know, but I come from a C++ background where these things were "da bomb" when I was first learning to implement them. Below is a class implementation for a queue (first-in-first-out) data structure that I used in a recent project at my workplace. I believe it should work for any type of data that's passed to it, as I used mySQL result objects and was able to pass the object from one page to another as a form element. # queue.php # Define the queue class class queue { # Initialize class variables var $queueData = array(); var $currentItem = 0; var $lastItem = 0; # This function adds an item to the end of the queue function enqueue($object) { # Increment the last item counter $this->lastItem = count($this->queueData); # Add the item to the end of the queue $this->queueData[$this->lastItem] = $object; } # This function removes an item from the front of the queue function dequeue() { # If the queue is not empty... if(! $this->is_empty()) { # Get the object at the front of the queue $object = $this->queueData[$this->currentItem]; # Remove the object at the front of the queue unset($this->queueData[$this->currentItem]); # Increment the current item counter $this->currentItem++; # Return the object return $object; } # If the queue is empty... else { # Return a null value return null; } } # This function specifies whether or not the queue is empty function is_empty() { # If the queue is empty... if($this->currentItem > $this->lastItem) # Return a value of true return true; # If the queue is not empty... else # Return a value of false return false; } } ?> # Examples of the use of the class # Make sure to include the file defining the class include("queue.php"); # Create a new instance of the queue object $q = new queue; # Get data from a mySQL table $query = "SELECT * FROM " . TABLE_NAME; $result = mysql_query($query); # For each row in the resulting recordset... while($row = mysql_fetch_object($result)) { # Enqueue the row $q->enqueue($row); } # Convert the queue object to a byte stream for data transport $queueData = ereg_replace("\"", """, serialize($q)); # Convert the queue from a byte stream back to an object $q = unserialize(stripslashes($queueData)); # For each item in the queue... while(! $q->is_empty()) { # Dequeue an item from the queue $row = $q->dequeue(); } -- http://www.php.net/manual/en/ref.classobj.php http://master.php.net/manage/user-notes.php?action=edit+21106 http://master.php.net/manage/user-notes.php?action=delete+21106 http://master.php.net/manage/user-notes.php?action=reject+21106

« previous php.notes (#29979) next »