我正在尝试从数据库中加载行,然后从中创建对象并将这些对象添加到私有(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/