Reputation: 37
I have started to learn Zend Framework 2 and I've got a problem with how to output the content of a variable from a class.
I wrote a simple class like below:
<?php
namespace example\Model;
class example{
protected $name = "sth";
public function show_name(){
echo $this-> name;
}
}
I instantiated it like below, in the Module.php file:
public function getServiceConfig()
{
return array(
'factories' => array(
// 'example\Model\example' => function($sm){
'example' => function($sm){
// $example_ = new example();
$example_ = new example\Model\example();
return $example_;
},
),
);
}
I wrote a controller like below:
namespace example\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class IndexController extends AbstractActionController
{
protected $show_example_;
public function indexAction()
{
return new ViewModel(array('example' => $this->show_example()));
// return array();
}
public function show_example()
{
if(!$this->show_example_){
$this->show_example_ = $sm->get('example\Model\exmaple');
}
return $this->show_example_;
}
I also wrote an index.phtml:
<?php
echo $example;
?>
Could I please ask you to help me with this?
Upvotes: 0
Views: 197
Reputation: 37
Thank you for your answer but the controller that you suggested me to replace my controller with is such a same as I wrote. Could I ask you to have a look at it once again?
In the error.log there is the information that:
PHP Notice: Undefined variable: example_ in /var/www/html/zf2-tutorial/module/example/view/example/index/index.phtml on line 3, referer: http://localhost/zf2-tutorial/module/example/view/example/index/
and
PHP Fatal error: Call to a member function show_name() on a non-object in /var/www/html/zf2-tutorial/module/example/view/example/index/index.phtml on line 3, referer: http://localhost/zf2-tutorial/module/example/view/example/index/
Upvotes: 0
Reputation: 25
I think the problem is in your Controller: You have
public function show_example()
{
if(!$this->show_example_){
$this->show_example_ = $sm->get('example\Model\exmaple');
}
return $this->show_example_;
}
And it should be:
public function show_example()
{
if(!$this->show_example_){
$this->show_example_ = $sm->get('example\Model\example');
}
return $this->show_example_;
}
By the way what is the error message?
Upvotes: 0
Reputation: 5803
Your class should not echo the name it should just return it:
<?php
namespace example\Model;
class example{
protected $name = "sth";
public function show_name(){
return $this->name;
}
}
then in your view you would do:
<?php
echo $example->show_name(); // outputs sth
?>
since $example
is an instance of your class "example" which contains the method show_name
which in turn returns the value "sth" which will be echoed by your view file
Upvotes: 1