2014-11-20 22 views
0

我已经开始学习Zend Framework 2,并且如何从类中输出变量的内容时遇到了问题。如何在ZF2中输出变量的内容?

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; 

?> 

请问请问请你帮助我?

+0

像@Jonathan如下所述,在'index.phtml','$ example'是一个实例你需要调用'show_name'方法而不是试图回显对象本身。 – 2014-11-21 10:43:20

回答

1

您的类不应该echo它应该只是回到它的名字:

<?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”这将回应您的查看文件

0

我认为问题是在您的C ontroller: 你有

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_; 
} 

到什么是错误消息的方式吗?

0

感谢您的回答,但您建议我更换控制器的控制器与我写的相同。我可以请你再看一遍吗?

在error.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/