[英]Fatal Error: Call to member function on non-object when it is an object
我有一個包含Classes數組的類。 循環遍歷數組並嘗試運行類函數時,我收到錯誤:
Fatal error: Call to a member function getTDs() on a non-object on line 21
這是我的代碼:
Cars.class
class Cars {
private $cars = array();
public function __construct(){
$result = DB::getData("SELECT * FROM `cars` ORDER BY `name`");
foreach($result as $row){
$this->cars[] = new Car($row);
}
}
public function printTable(){
$html = '<table>';
for($i=0, $l=count($this->cars); $i<$l; $i++){
$html .= '<tr>';
$html .= $this->cars[$i]->getTDs();
$html .= '<td></td>';
$i++;
//print_r($this->cars[$i]);
//print_r($this->cars[$i]->getTDS());
$html .= $this->cars[$i]->getTDs(); //This is the supposed non-object
$html .= '<td></td>';
$i++;
$html .= $this->cars[$i]->getTDs();
$html .= '</tr>';
}
$html .= '</table>';
echo($html);
}
}
Car.class
class Car {
public $data;
public function __construct($data){
$this->data = $data;
}
public function getTDs(){
$html = '<td>'.$this->data['name'].'</td>';
return $html;
}
}
當在“非對象”(第19行)上使用print_r
時,我得到了這個:
Car Object
(
[data] => Array
(
[name] => 'Ferrari'
)
)
在調用getTDs()
(第20行)的“非對象”上使用print_r
時,我得到:
<td>Ferrari</td>
那么,當我嘗試將該結果添加到我的$html
變量時,在下一行中它會怎樣?
您的陳述是:
for($i=0, $l=count($this->cars); $i<$l; $i++){
但是在這個循環中,你再增加兩倍$i
。
$i++;
$i++;
因此,在循環的最后一次迭代中, $i
指向cars
的最后一個元素,但是當你再次遞增$i
時,你已經超過了數組的末尾。
所以在你到達太遠之前停止循環。 你的修復應該是:
for($i=0, $l=count($this->cars)-2; $i<$l; $i++){
編輯每次嘗試訪問索引時,檢查是否位於cars
數組的末尾更為明智。
你在循環中增加索引,這是你不需要做的。 這應該工作正常:
for($i=0, $l=count($this->cars); $i<$l; $i++){
$html .= '<tr>';
$html .= $this->cars[$i]->getTDs();
$html .= '<td></td>';
$html .= "</tr>";
}
另外,作為最佳實踐,嘗試使用count outside循環,它具有更好的性能。
$numCars = count($this->cars);
for($i=0; $i<$numCars; $i++)
{
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.