Can anyone explain the benefit of PHP's compact() function accepting the string of 'a variable with that name' instead of the actual variable?
For example:
$foo = 'foo'; $bar = 'bar'; $compacted = compact('foo', 'bar');
Why do I need to pass a string of the variable name instead of just passing the variable itself and PHP handling mapping this to an array? Like so:
$compacted = compact($foo, $bar);
PHP | compact() Function The compact() function is an inbuilt function in PHP and it is used to create an array using variables. This function is opposite of extract() function. It creates an associative array whose keys are variable names and their corresponding values are array values.
Definition and Usage The compact() function creates an array from variables and their values. Note: Any strings that does not match variable names will be skipped.
The compact() function is used to convert given variable to to array in which the key of the array will be the name of the variable and the value of the array will be the value of the variable.
A string is series of characters, where a character is the same as a byte. This means that PHP only supports a 256-character set, and hence does not offer native Unicode support. See details of the string type. Note: On 32-bit builds, a string can be as large as up to 2GB (2147483647 bytes maximum)
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'));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With