Why am I getting a "Call to a member function on a non-object" error?
I'm working with the Zend framework, backed by MySQL, and trying to set up an index view. However, with the code I have, I keep getting the "call to a member function on a non-object" error and I don't know how to solve it. Here's the Controller for my index page:
开发者_开发问答 public function indexAction() {
$dImage = new Application_Model_DImage();
}
Here's the code for the DImage model that it references:
public function getImageDesCol ($Id) {
return $this->getDb()->fetchCol("SELECT description FROM d_image WHERE d_id = ?", $Id);
}
Finally, here's the source of my Index view page where I'm trying to display the values from the DImage model:
<?php $description = $this->dImage->getImageDesCol($id) ?>
<label><?php echo $description[0] ?></label>
When I load that page, I get the "Call to a member function getImageDesCol()
on a non-object" error instead of a rendered page. Since I'm new to the Zend framework and PHP in general, I feel like there's something obvious that I'm missing. What can I do to fix this?
Change:
public function indexAction()
{
$dImage = new Application_Model_DImage();
}
To:
public function indexAction()
{
$this->dImage = new Application_Model_DImage();
}
You must add the Application_Model_DImage object to the view, or else the view does not know of an object with that name. Do this:
public function indexAction()
{
$dImage = new Application_Model_DImage();
$this->view->dImage = $dImage;
}
Then you will have your $dImage available to your view scripts.
Your view scripts execute in the context of a Zend_View object, but you were creating your Application_Model_DImage object in the context of your controller (an instance of Zend_Controller_Action). As such, you need to explicitly pass to the view whatever objects the view scripts will use. By default, Zend_Controller_Action has a view object ready for you (check here).
精彩评论