【问题标题】:Getting contents with extract($variables), but the variables are undefined使用 extract($variables) 获取内容,但变量未定义
【发布时间】:2015-08-13 16:00:33
【问题描述】:

我还没有掌握 extract() 函数和传输变量的窍门。 我在用户控制器中有一个方法,其中定义了一些变量,并以数组的形式发送到父控制器中的视图函数,其中提取了数组。然后需要视图。但是变量结果是未定义的。但是可以打印数组内容。

这是具有简化配置文件功能的用户控制器:

class User extends Controller{

    public function profile(){

         $profiledetails = $this->profiledetails();           
         $profilestatus = $this->profileStatus();            

         $this->view('profile', [$profiledetails, $profilestatus]);
}}    

变量被发送到父Controller中的视图函数:

class Controller {
    public function view($view, $variables =[]){                    

    extract($variables);

    require_once './app/views/' . $view . '.php';
}}

在视图中,“profile.php”显示未定义变量错误。我认为“extract()”函数会使 $profiledetails 和 $profilestatus 在视图中作为变量可用。 我究竟做错了什么?也许我使用了错误类型的数组,或者我应该使用“variabe variables”之类的......(在这种情况下,如何?)。

【问题讨论】:

标签: php arrays variables model-view-controller extract


【解决方案1】:

extract关联数组一起使用。

    $this->view('profile', 
      [
        'profiledetails' => $profiledetails, 
        'profilestatus' => $profilestatus
      ]);   

【讨论】:

  • 非常棒。谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-04-10
  • 2015-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-06
相关资源
最近更新 更多