可能重复:
调用非对象上的成员函数
我尝试从 CakePHP 应用程序的视图中调用模型中的辅助函数“getColition($id)”,但出现此错误:
Fatal error: Call to a member function getCoalition() on a non-object
in C:\xampp\htdocs\MyCakeApp\app\View\Candidates\index.ctp on line 32
我认为这可能与常见的 MVC 有关,但我无法弄清楚。应用程序是一个小型的“选举”应用程序。任何一般的辅助功能都会出现类似的问题。
为什么我不能在模型中调用函数?模型是辅助功能的合适位置吗?
/app/Model/Candidate.php
<?php
/**
* @property
*/
class Candidate extends AppModel {
var $name = 'Candidates';
// THIS I WANT TO CALL
public function getCoalition($id){
$results = $this->Candidate->query("SELECT coalitions.name from candidates, coalitions where candidates.coalition_id = coalitions.id and candidates.id =$id");
return $results;
}
}
?>
/app/Controller/CandidatesController.php
<?php
class CandidatesController extends AppController {
public $helpers = array('Html', 'Form');
public $components = array('Session');
var $name = 'Candidates';
public function index() { //index stuff... }
public function add() { //add stuff...}
public function edit($id = null) { //edit stuff...}
public function delete($id) { //delete stuff...}
}
?>
/app/View/Candidate/index.ctp
<h1>Candidates</h1>
<p><?php echo $this->Html->link("Add candidate", array('action' =>'add'), array('class' => 'btn btn-primary')); ?></p>
<hr>
<table>
<tr>
<th>Name</th>
<th>Coalition</th>
</tr>
<?php foreach ($candidates as $candidate): ?>
<tr>
<td><?php echo $candidate['Candidate']['name']; ?></td>
<td>
<?php
///////////////// THIS CREATES THE ERROR /////////////////
echo $this->Candidate->getCoalition($candidate['Candidate']['coalition_id']);
?>
</td>
<td><?php
echo $candidate['Candidate']['votes'];
echo $this->Html->link('Muokkaa', array('action' => 'edit', $candidate['Candidate']['id']));
?>
</td>
</tr>
<?php endforeach; ?>
</table>