i'm searching for a solution in PHP to use a function which can use several arguments without defining in advance the number of arguments. I know there is the function func_get_args(), but it's not quite enough... In my case i have a function that render a template with twig, and I want to give context to the template, I've made that but it's not realy proper beacause if the order of arguments change when I call the function everything is broken...
Someone have a solution?...
Thanks for your time!
public function render_with_context()
{
$args = func_get_args();
$context['loged'] = $args[0];
$context['agencies'] = $args[1];
$context['login'] = $args[2];
$context['password'] = $args[3];
$context['active_agencies'] = $args[4];
\Timber\Timber::render('views/admin.html.twig', $context);
}
My Answer:
You can use the func_get_args() function along with a loop to dynamically assign the arguments to the context array. Here's an example of how you can modify your function to achieve this:
php
public function render_with_context()
{
$args = func_get_args();
$context = [];
foreach ($args as $index => $arg) {
$context['arg_' . $index] = $arg;
}
\Timber\Timber::render('views/admin.html.twig', $context);
}
With this modification, you can pass any number of arguments to the function and they will be dynamically assigned to the context array with keys like "arg_0", "arg_1", etc. This way, the order of arguments won't matter and your function will still work correctly.
Rate this post
3 of 5 based on 8367 votesComments