5
According to the PHP documentation, the function compact
.
For each of the parameters passed,
compact()
looks for a variable with the name specified in the symbol table and adds it in the output array so that the variable name will be the key and its contents will be the value for this key.
I mean, she can create a array
based on local scope variable names.
I usually use this function in some cases to transform into array
some values I’m using in variables.
For example:
function process_request(array $data) {
$body = $data['response']->getBody();
$headers = $data['request']->getHeaders();
// Resto do código
}
$request = new Request;
$response = new Response;
process_request(compact('response', 'request'));
In the specific case above, it could also be done with literal assignment of a array
:
process_request(['response' => $response, 'request' => $request])
I use to compact
rather than direct attribution simply because of aesthetics (vanity with the code). But it comes to my mind that compact
is a function, no direct assignment, and that this may imply in performance.
So I ask you:
Which of the two forms are the most appropriate?
All versions of PHP are compatible with the function
compact
?For
compact
be a function, not a language constructor, the Form slower than literal assignment?
I don’t quite understand the function of
compact
, it searches for variables in the same scope with the same names passed and converts them into an array with the respective values?– RFL
@Rafaelacioly yes, exactly. You’ve never used it, right :p
– Wallace Maxters