tags:

views:

66

answers:

3

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.

+3  A: 

Try

$this->stationListing

inside the class ;)

To access class members you always have to use the "magic" $this self-reference of the current instance. Note: When you're accessing static members like that you have to use self:: instead (or static:: starting in PHP 5.3, but that's another story).

Franz
+1  A: 

$stationListing in the constructor is referencing a local variable, not the one in your class. Change it to the following:

function __construct() {
...
$this->stationListing = array();
...
array_push($this->stationListing, $station);
Andy Shellam
A: 

Thank you very much for your replies. This was an embarrassing oversight! :)

Alex
don't forget to accept an answer!
Sirber