Jump to content

[SOLVED] storing objects in arrays


|BLAND|

Recommended Posts

I have been struggling with this all day. I spent hours searching and have yet found a solution that works for me. All I want to do is store objects into a array.

 

class Inventory 
{   
   public $container = array();
   public function storeProducts($Q)
   {
         $MyDB = new Database(); //previously defined object.
         $MyDB->query = 'SELECT * FROM inventory';
         $MyDB->Connect();
         $MyDB->Query();

         if($MyDB->result)
         {
            while($row = mysql_fetch_array($MyDB->result))
            {
               $test = new Product(); //previously defined object.
               $test->clas = $row['CLASS'];
               print($test->clas); //used for testing
               print("<br>");    //used for testing
               $test->name = $row['NAME'];
               $test->manu = $row['MANUFACTURER'];
               $test->engine = $row['EGN'];
               $test->price = $row['PRICE'];
               $test->serial = $row['SERIAL_NO'];
               $test->description = $row['DESCRIPTION'];
               $container[] = $test; //PROBLEM 
            }
            echo "Items are stored into array <br>";
         }
         else
            echo "No Results Found";
      }

   public function viewContainer()
   {
      $total = count($container);
      print_r($container);
      print($total);
   }

 

My output is "0" for $total and nothing from print_r()

 

I have also tried using "array_push($container, $test)"

I get an error stating that the first parameter needs to be a array? Is $container not defined as an array? Any help would be greatly appreciated. Thanks.

 

You can also see the results by visiting pwb3.com\products.php

 

Link to comment
https://forums.phpfreaks.com/topic/174409-solved-storing-objects-in-arrays/
Share on other sites

in order to view the value of $container using this function

   public function viewContainer()
   {
      $total = count($container);
      print_r($container);
      print($total);
   }

you actually need to give the variable to that function

 

like this

   public function viewContainer($argument)
   {
      $total = count($argument);
      print_r($argument);
      print($total);
   }

 

then you can use the function

viewContainer($container);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.