php - 使用 extract($variables) 获取内容,但变量未定义

标签 php arrays variables model-view-controller extract

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

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

class User extends Controller{

    public function profile(){

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

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

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

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

    extract($variables);

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

并且在 View “profile.php”中,显示了 undefined variable 错误。我认为“extract()”函数将使 $profiledetails 和 $profilestatus 在 View 中作为变量可用。 我究竟做错了什么?也许我使用了错误类型的数组,或者我应该使用“可变变量”或其他东西……(在那种情况下,如何?)。

最佳答案

extract 使用关联数组

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

关于php - 使用 extract($variables) 获取内容,但变量未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30552397/

相关文章:

php - 日历脚本 PHP

PHP 7 : Missing VCRUNTIME140. DLL

javascript - 为什么 Array.apply(null, [args]) 在处理稀疏数组时表现不一致?

php - 在 PHP 中反向堆叠变量

此处不允许 java.util.Scanner 对象声明

javascript - jquery 通过 foreach 生成事件

PHP 使用 str_replace 将数字更改为字符串而不混淆

python - Numpy 数组 : Efficient use of arrays containing indices

java - java中是否有任何函数可以在索引 i 和索引 j (两者都包含)之间的数组中执行循环左移

java regex - 存储在变量中的字符串的匹配部分