[英]Fatal Error: Call to member function on non-object when it is an object
I have one class that holds an array of Classes. 我有一个包含Classes数组的类。 When looping through the array and trying to run Class functions, I get the error:
循环遍历数组并尝试运行类函数时,我收到错误:
Fatal error: Call to a member function getTDs() on a non-object on line 21
Here is my code: 这是我的代码:
Cars.class 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 Car.class
class Car {
public $data;
public function __construct($data){
$this->data = $data;
}
public function getTDs(){
$html = '<td>'.$this->data['name'].'</td>';
return $html;
}
}
When using print_r
on that "non-object" (line 19) I get this: 当在“非对象”(第19行)上使用
print_r
时,我得到了这个:
Car Object
(
[data] => Array
(
[name] => 'Ferrari'
)
)
When using print_r
on the "non-object" calling getTDs()
(line 20) I get this: 在调用
getTDs()
(第20行)的“非对象”上使用print_r
时,我得到:
<td>Ferrari</td>
So how come when in the very next line when I try to add that result to my $html
variable it breaks? 那么,当我尝试将该结果添加到我的
$html
变量时,在下一行中它会怎样?
Your for statement is: 您的陈述是:
for($i=0, $l=count($this->cars); $i<$l; $i++){
But inside that loop, you are incrementing $i
twice more. 但是在这个循环中,你再增加两倍
$i
。
$i++;
$i++;
So at the last iteration through the loop, $i
points to the last element of cars
, but when you increment $i
again, you're reaching past the end of the array. 因此,在循环的最后一次迭代中,
$i
指向cars
的最后一个元素,但是当你再次递增$i
时,你已经超过了数组的末尾。
So stop the loop before you reach too far. 所以在你到达太远之前停止循环。 Your fix should be:
你的修复应该是:
for($i=0, $l=count($this->cars)-2; $i<$l; $i++){
Edit It is smarter to check if you're at the end of the cars
array every time you attempt to access an index. 编辑每次尝试访问索引时,检查是否位于
cars
数组的末尾更为明智。
You're incrementing your index inside the loop, which you do not need to do. 你在循环中增加索引,这是你不需要做的。 This should work fine:
这应该工作正常:
for($i=0, $l=count($this->cars); $i<$l; $i++){
$html .= '<tr>';
$html .= $this->cars[$i]->getTDs();
$html .= '<td></td>';
$html .= "</tr>";
}
Also, as a best practice, try using count outside loops, it has better performance. 另外,作为最佳实践,尝试使用count outside循环,它具有更好的性能。
$numCars = count($this->cars);
for($i=0; $i<$numCars; $i++)
{
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.