0

I would like to make cross variables in my template via the router.

I want to do:

$router->with(array(...));

Here is my with function:

public function with($vars)
{
    if(is_array($vars))
    {
        foreach ($vars as $key => $value)
        {
           $$key = $value;
        }
    }else
    {
        die("La fonction with() demande un tableau en paramètre.");
    }
}

Am I on the right track?

3
  • 3
    I wouldn't create all those variables. Just use the array and access the data with the key. Commented Aug 4, 2016 at 17:00
  • utterly useless, since those variables would exist ONLY within your with() function, and be destroyed as soon as the function exits. Commented Aug 4, 2016 at 17:24
  • yeah, I forgot the extract() function. Everything is revised and functional, thank you Commented Aug 4, 2016 at 17:58

1 Answer 1

1

You can instead just extract your keys as vars in your template. Like this

function with($view, array $data = []) {
    extract($data);
    require $view . '.php';
}

with('some_view', [
    'name' => 'John Doe'
]);

Then you can use it in your view, like so

<h1><?= $name ?></h1>
Sign up to request clarification or add additional context in comments.

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.