Why does PHP compact() use strings instead of actual variables?

compact is a function and not a language construct. There is no way for PHP functions to know the names of the variables passed to them. In theory, compact could be implemented as a language construct like unset or isset and work the way you described. But that's not what happened.


Because the compact() function needs to know the names of the variables since it is going to be using them as array keys. If you passed the variables directly then compact() would not know their names, and would not have any value to use for the returned array keys.

However, I suggest building the array manually:

$arr = array(
    'foo' => $foo,
    'bar' => $bar);

I consider compact() deprecated and would avoid using it in any new code.


As far as benefits, I've found compact() to be useful in MVC applications. If you're writing controller code and you need to pass an associative array of variables and their apparent names that you've set in your controller to the view, it shortens something like:

View::make('home')->with(array('products' => $products, 'title' => $title, 'filter' => $filter'));

to

View::make('home')->with(compact('products', 'title', 'filter'));

Tags:

Php