0

When writing controllers for Symfony 2, I often need to pass quite a few variables to the template like return array('param1' => $param1, 'anotherBigParam' => $anotherBigParam, 'yetAnotherParam' => $yetAnotherParam);

With many parameters this ends up really long and ugly, so I thought about creating a helper function for it:

public function indexAction()
{
    $param1 = 'fee';
    $anotherBigParam = 'foe';
    $yetAnotherParam = 'fum';
    return $this->vars('param1', 'anotherBigParam', 'yetAnotherParam');
}

private function vars() {
    $arr = array();
    foreach(func_get_args() as $arg) {
        $arr[$arg] = $$arg;
    }
    return $arr;
}

Is there some kind of drawback or risk from doing this? Does PHP or Symfony 2 already provide a better or cleaner way to achieve the same result?

2 Answers 2

3

There is a native way of doing it: compact

$one = 'ONE';
$two = 'TWO';
$a = compact( 'one', 'two' );
print_r( $a );
/*
Array
(
    [one] => ONE
    [two] => TWO
)
*/
Sign up to request clarification or add additional context in comments.

Comments

2

You're looking for compact.

public function indexAction()
{
    $param1 = 'fee';
    $anotherBigParam = 'foe';
    $yetAnotherParam = 'fum';
    return compact('param1', 'anotherBigParam', 'yetAnotherParam');
}

4 Comments

I knew there had to be a native way! Thanks for both of the answers, I'll accept this one for it's ninja speed as soon as accepting becomes possible.
@Kaivosukeltaja: PHP's got tons of built-in functions :-P
@Rocket: True, it's a haystack of useful built-in functions and finding the right ones can be really challenging if it's a rarely needed one. I read through the list of array functions but skipped compact because it sounded more like it has something to do with compression...
@Kaivosukeltaja: Yeah, some functions have interesting names. Like explode/implode.

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.