Php 当我从数组中检索对象时,对象数组为空
我试图从数据库加载行,然后从中创建对象,并将这些对象添加到私有数组中 以下是我的课程:Php 当我从数组中检索对象时,对象数组为空,php,mysql,oop,Php,Mysql,Oop,我试图从数据库加载行,然后从中创建对象,并将这些对象添加到私有数组中 以下是我的课程: <?php include("databaseconnect.php"); class stationItem { private $code = ''; private $description = ''; public function setCode($code ){ $this->code = $code; } public
<?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];
}
}
?>
我发现构造函数末尾的sizeof($stationList)是1,但当我们尝试使用索引从数组中获取对象时,它是零。因此,我得到的错误是:
致命错误:对非对象调用成员函数getCode()
有人能给我解释一下为什么会这样吗?我想我误解了对象引用在PHP5中的工作方式。试试看
$this->stationListing
在班里;)
要访问类成员,您必须始终使用当前实例的“magic”$this
自引用。注意:当您访问这样的静态成员时,您必须使用self::
(或者从PHP5.3开始使用static::
,但这是另一种情况)。试试看
$this->stationListing
在班里;)
要访问类成员,您必须始终使用当前实例的“magic”
$this
自引用。注意:当您访问这样的静态成员时,您必须使用self::
(或从PHP5.3开始的static::
,但这是另一种情况)。$stationListing
在构造函数中引用的是局部变量,而不是类中的变量。将其更改为以下内容:
function __construct() {
...
$this->stationListing = array();
...
array_push($this->stationListing, $station);
构造函数中的
$stationListing
引用的是局部变量,而不是类中的局部变量。将其更改为以下内容:
function __construct() {
...
$this->stationListing = array();
...
array_push($this->stationListing, $station);