繁体   English   中英

致命错误:当它是一个对象时,调用非对象上的成员函数

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM