php - 当我从数组中检索一个对象时,对象数组是空的

标签 php mysql oop

我正在尝试从数据库中加载行,然后从中创建对象并将这些对象添加到私有(private)数组中。

这是我的类(class):

<?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 对象(目前有一个代码和描述),然后我将它们推送到我的数组的末尾,该数组作为一个私有(private)变量保存在 stationList 中。

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

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

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

fatal error :在非对象上调用成员函数 getCode()

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

最佳答案

尝试

$this->stationListing

在类里面;)

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

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

相关文章:

php - 如何更改 !isset 语句

php - php 中的表单 javascript 中的验证

html - 对于动态内容生成器来说,将 HTML 保存到 MySQL 数据库是一个好方法吗?

Javascript:链接列表:无法删除对象引用

php - HTML 电子邮件显示为代码而不是 css 页面

当正文中有 url a 标签时 PHP 邮件无法发送

mysql - 查找重复项的查询

php - 在mysql中的行中显示相同的值并打印列值及其在php中的计数

java - 如何为不同的表示层设计应用程序?

R:何时使用 setGeneric 或在命名空间中导出 s4 方法