php $ this-> view-> $ someVar有可能吗?

时间:2012-09-03 19:19:12

标签: php oop variable-assignment

我正在创建一个模型视图控制器框架,并且我是一种新的东西。我想将变量从控制器传递给视图。我的View.php构造函数如下所示:

    function __construct($file, $args) {
        $this->view = $file;
         foreach($args as $key => $arg) {
            $this->view->$key = 'awda';
         }
    }

它给我错误原因

 $this->view->$key is not a valid statement. 

如果我从Controller那样做

 $this->view->hello = 'hello world' 

我回音

 $this->hello 

在视图中它工作正常,但我希望能够传入多个变量。有没有人知道更好的方法呢?谢谢

1 个答案:

答案 0 :(得分:3)

您正在尝试将属性分配给我怀疑是字符串($file)。由于您位于视图的构造函数中,因此只需使用$this来引用视图:

function __construct($file, $args) {
    $this->view = $file;
     foreach($args as $key => $arg) {
        $this->view->$key = 'awda'; // HERE is the issue.. isn't $this->view a string?
     }
}


function __construct($file, $args) {
    $this->view = $file;
     foreach($args as $key => $arg) {
        $this->$key = 'awda'; // assign $key as property of $this instead...
     }
}
相关问题