PHP: Array of objects is empty when I come to retrieve one from the array

Posted by Tom on Stack Overflow See other posts from Stack Overflow or by Tom
Published on 2010-04-13T08:37:42Z Indexed on 2010/04/13 8:42 UTC
Read the original article Hit count: 353

Filed under:
|
|
|

Good morning,

I am trying to load rows from a database and then create objects from them and add these objects to a private array.

Here are my classes:

<?php

include("databaseconnect.php");

class stationItem {
    private $code = '';
    private $description = '';


    public function setCode($code ){
        $this->code = $code;
    }

    public function getCode(){
        return $this->code;
    }

    public function setDescription($description){
        $this->description = $description;
    }

    public function getDescription(){
        return $this->description;
    }

}


class stationList {
    private $stationListing;

    function __construct() {
        connect();
        $stationListing = array();

        $result = mysql_query('SELECT * FROM stations');

        while ($row = mysql_fetch_assoc($result)) {
            $station = new stationItem();
            $station->setCode($row['code']);
            $station->setDescription($row['description']);

            array_push($stationListing, $station);
        }
        mysql_free_result($result);
    }


   public function getStation($index){
        return $stationListing[$index];
   }
}

?>

As you can see I am creating a stationItem object per database row (which for now has a code and description) and I then push these on to the end of my array which is held as a private variable in stationList.

This is code which creates this classes and attempts to access the properties on them:

$stations = new stationList();
$station = $stations->getStation(0);
echo $station->getCode();

I am finding that the sizeof($stationList) at the end of the constructor is 1 but then it is zero when we come to try to get an object from the array using the index. Therefore the error that I get is:

Fatal error: Call to a member function getCode() on a non-object

Please can someone explain to me why this is happening? I guess I am misunderstanding how object references work in PHP5.

© Stack Overflow or respective owner

Related posts about php

Related posts about php5