返回列表 发帖

能不能在controller对象的构造函数里设定一个smarty对象的属性

  1. class main extends spController{
  2.     //需要一个smarty对象的style属性

  3.     public function index(){
  4.         $this->display($this->style.'/'.$__controller.'/'.$__action.'.html');
  5.     }
  6. }
复制代码

构造函数是__construct,如果需要在控制器的构造函数里面获取smarty对象并进行操作,可以用$this->getView()来获取。

TOP

  1. public function main extends spController{
  2.     public function __construct(){
  3.         $smarty = $this->getView();
  4.         $smarty->style = 'blue';
  5.     }
  6. }
复制代码



提示:

Fatal error: Call to a member function getView() on a non-object

TOP

要注意,在使用控制器或者模型类的构造函数,一定要加上parent::__construct();

public function main extends spController{
    public function __construct(){
         parent::__construct();
        $smarty = $this->getView();
        $smarty->style = 'blue';
    }
}

参见微博实例的general控制器的构造函数

TOP

对OO了解不够深刻  构造函数不是在实例化类的时候就会执行的吗  怎么还要在函数中调用一下自身?
另外这样在别的函数中还是无法调用该属性

  1. class main extends spController{
  2.     public function __construct(){
  3.         parent::__construct();
  4.         $smarty = $this->getView();
  5.         $smarty->style = 'blue';
  6.     }
  7.     public function index(){
  8.         echo $this->style;
  9.     }
  10. }
复制代码

TOP

哦  明白了  parent代表的是spController对象  但为什么还是输出不了呢?

TOP

$smarty->style = 'blue';

这是什么?smarty对象没有style这个成员变量吧?你要用$this->style

TOP

  1. class main extends spController{
  2.     public function __construct(){
  3.         parent::__construct();
  4.         $this->style = 'blue';
  5.     }
  6.     public function index(){
  7.         echo $this->style;
  8.     }
  9. }
复制代码


还是不行

TOP

  1. class main extends spController{
  2.     public $style = '';
  3.     public function __construct(){        parent::__construct();
  4.         $this->style = 'blue';
  5.     }
  6.     public function index(){
  7.         $this->display($this->style.'/'.$__controller.'/'.$__action.'.html');
  8.     }
  9. }
复制代码
这样可以了  但是在模板文件中使用变量没办法显示:
<{$style}>
输出为空

TOP

这样可以了  但是在模板文件中使用变量没办法显示:

输出为空
stalker 发表于 2010-3-11 10:59


可以参考一下winblog微博实例的geranel控制器,里面有非常多的模板变量的辅助之类的操作,很有参考价值。

TOP

返回列表