3

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?

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

$viewData needs to be an associative array. The keys of the array will be names of the variables once they have been "extracted".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.