我已经开始学习Zend Framework 2,但是在如何从类输出变量内容方面遇到了问题。
I wrote a simple class like below:
<?php
namespace example'Model;
class example{
protected $name = "sth";
public function show_name(){
echo $this-> name;
}
}
我在 Module.php 文件中像下面这样实例化它:
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_;
},
),
);
}
我写了一个控制器,如下所示:
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_;
}
我还写了一个index.phtml:
<?php
echo $example;
?>
我能请你帮我解决这个问题吗?
你的类不应该回显它应该返回它的名称:
<?php
namespace example'Model;
class example{
protected $name = "sth";
public function show_name(){
return $this->name;
}
}
那么在您看来,您将执行以下操作:
<?php
echo $example->show_name(); // outputs sth
?>
由于$example
是类"示例"的一个实例,其中包含方法show_name
,该方法又返回值"sth",该值将由您的视图文件回显
我认为问题出在您的控制器上:你有
public function show_example()
{
if(!$this->show_example_){
$this->show_example_ = $sm->get('example'Model'exmaple');
}
return $this->show_example_;
}
它应该是:
public function show_example()
{
if(!$this->show_example_){
$this->show_example_ = $sm->get('example'Model'example');
}
return $this->show_example_;
}
顺便问一下错误消息是什么?
感谢您的回答,但您建议我替换控制器的控制器与我写的相同。我能请你再看一遍吗?
在错误中.log有以下信息:
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/
和
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/