我试图从数据库中加载行,然后从中创建对象并将这些对象添加到私有数组。

这是我的课程:

<?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];
   }
}

?>


如您所见,我正在为每个数据库行创建一个stationItem对象(现在有一个代码和说明),然后将它们推到数组的末尾,该数组作为stationList中的私有变量保存。

这是创建此类并尝试访问其属性的代码:

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


我发现构造函数末尾的sizeof($ stationList)为1,但是当我们尝试使用索引从数组中获取对象时,它为零。因此,我得到的错误是:

致命错误:在非对象上调用成员函数getCode()

请有人可以向我解释为什么会这样吗?我想我误会了PHP5中对象引用的工作方式。

最佳答案

尝试

$this->stationListing


在班级内部;)

要访问类成员,您始终必须使用当前实例的“魔术” $this自引用。注意:当您访问类似的静态成员时,必须使用self::(或从PHP 5.3开始的static::,但这是另一回事)。

关于php - 当我从数组中检索对象时,对象数组为空,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2628096/

10-12 07:40
查看更多