Reputation: 21430
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?
Upvotes: 3
Views: 2648
Reputation: 17390
$viewData
needs to be an associative array. The keys of the array will be names of the variables once they have been "extracted".
Upvotes: 2
Reputation: 270617
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.
Upvotes: 5