According to the PHP documentation, the function compact
.
For each of the passed parameters,
compact()
looks for a variable with the name specified in the symbol table and adds it to the output array so that the variable name will be the key and its contents will be the value for this variable key.
That is, it can create a array
based on the names of the variables of the local scope.
I usually use this function in some cases to be able to transform some of the values I'm using into variables into array
.
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 attribution of a array
:
process_request(['response' => $response, 'request' => $request])
I usually use compact
instead of direct attribution simply because of aesthetics (vanity with code). But it sometimes comes to my mind that compact
is a function, since direct assignment is not, and that may imply performance.
So, I ask:
-
Which of the two forms are most appropriate?
-
All PHP versions support the
compact
function?