【问题标题】:php $this->view->$someVar is it possible?php $this->view->$someVar 有可能吗?
【发布时间】:2012-08-28 11:53:45
【问题描述】:

我正在创建一个模型视图控制器框架,我对此有点陌生。我想将变量从控制器传递到视图。我的 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. 

如果我从控制器做类似的事情

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

我做回声

 $this->hello 

鉴于它工作正常,但我希望能够传入多个变量。有谁知道这样做的更好方法?谢谢

【问题讨论】:

  • $this->view->{$key} 应该可以工作
  • 现在我收到警告:尝试在此分配非对象的属性

标签: php oop variable-assignment


【解决方案1】:

您正在尝试将属性分配给我怀疑是字符串 ($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...
     }
}

【讨论】:

  • 谢谢,您节省了我另外 1 小时盯着我的代码并试图弄清楚事情的时间。 :) 非常感谢,现在成功了
猜你喜欢
  • 1970-01-01
  • 2021-03-26
  • 2011-03-19
  • 1970-01-01
  • 1970-01-01
  • 2019-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多