Jason Van Malder Jason Van Malder - 4 months ago 18
PHP Question

PHP - function which initializes variables

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?

Answer

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>