Fatal error: Call to a member function first() on a non-object

Fatal error: Call to a member function first() on a non-object

是的,我知道有很多关于这个主题的问题,我搜索并尝试了所有答案,但 none 对我有帮助。 这就是为什么我用自己的代码创建了另一个问题。

class Student{
    private $_db,
            $_first;

public function __construct() {
    $this->_db = DB::getInstance();
}

public function getLast($fields = array()) {
    $columns = 'admission_no, id';
    $orderBy = 'id';
    $order = 'DESC';

    if(!empty($fields['columns'])){
        $columns = $fields['columns'];
    }

    if(!empty($fields['order_by'])){
        $orderBy = $fields['oder_by'];
    }

    if(!empty($fields['order'])){
        $order = $fields['order'];
    }

    $data = $this->_db->query("SELECT {$columns} FROM students ORDER BY {$orderBy} {$order} LIMIT 1");

    if($data->count()){
        $this->_first = $data->first();
        return true;
    }
    return false;
}

public function first() {
    return $this->_first;
}

}

以上是学生Class的代码。 在下面的代码中,我调用 Student class,而调用 Student class 时出现此错误。

$student = new Student;

$admission = $student->getLast()->first();
$admission_no = $admission->admission_no;

echo $admission_no;

你们能给我任何提示或线索吗? 任何帮助将不胜感激。

谢谢!

$admission = $student->getLast()->first();

这段代码非常糟糕。您在方法 getLast() 的结果上调用方法 first() 而不是在 $student 对象上。 getLast() return true 或 false 肯定不是对象。尝试:

$student->getLast();
$admission = $student->first();

如果要调用链式方法,则必须对每个方法 return $this。 即:

 class FormHelper {

    protected $input;
    protected $type;
    protected $name;

    public function input() {
        $this->input = '<input ';
        return $this;
    }

    public function type($type) {
        $this->type = $type;
        return $this;
    }

    public function name($name) {
        $this->name = $name;
        return $this;
    }

    public function render() {
        $out = "{$this->input} type=\"{$this->type}\" name=\"{$this->name}\" />";
        echo $out;
    }

  }

  $form = new FormHelper();

  $form->input()->type('text')->name('email')->render();