PHP Extract Not Working on Array

extract, oop, php

Solution

`extract()` expects an associative array, so it has keys from which to derive variable names in the scope it's called.

// Pass in an associative array
$viewData = array(
  'hasImages' => $hasImages->arr,
  'latest' => $latest->arr,
  'mostViewed' => $mostViewed->arr,
  'all' => $all->arr, 
  'error' => $this->error
);

// After extract(), will produce
$hasImages
$latest
$mostViewed
$all
$error

However, I would question the utility of using `extract()` at all. Instead, it may be more readable to use the associative array as above, and access it via keys like `$var['mostViewed']['something']` inside your method.

Problem

I am trying to get my $viewData into local variables. Here is my function: ``` function view($layout, $view, $var) { extract($var); include($layout); } ``` Here is how I am using it: ``` $viewData = array($hasImages->arr, $latest->arr, $mostViewed->arr, $all->arr, $this->error); $this->view('/view/shared/layout.php', '/view/home.php', $viewData); ``` The extract method works fine on the $this->error string, but not on any of the arrays such as $hasImages->arr. It doesn't seem to create the variable in the local context. How can I get my arrays into my function?

Original source