是的,我知道有很多关于这个主题的问题,我搜索并尝试了所有答案,但没有一个帮助我。这就是为什么我用自己的代码创建了另一个问题。
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;
}
}
以上是学生班的代码。在下面的代码中,我正在调用学生类,在调用学生类时出现此错误。
$student = new Student;
$admission = $student->getLast()->first();
$admission_no = $admission->admission_no;
echo $admission_no;
你们能给我任何提示或线索吗?任何帮助将不胜感激。
谢谢!
$admission = $student->getLast()->first();
这段代码是完全糟糕的。在方法 getLast() 的结果上调用方法 first(),而不是在对象上$student。getLast() 返回 true 或 false 这肯定不是对象。尝试:
$student->getLast();
$admission = $student->first();
如果要调用链接的方法,则必须在每个方法上返回$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();