Difference between Compact function and literal array assignment

Asked

Viewed 572 times

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?

  • @Rafaelacioly yes, exactly. You’ve never used it, right :p

2 answers

3

  • I don’t think you will find any performance gains using any of the available methods to the detriment of others. This really comes down to legibility and what makes the most sense when looking at the code.
  • The function is available from version PHP 4, PHP 5, PHP 7.
  • I use the compact() in Laravel 5 for the development of a RP system and I have no problem as to the slowness.

-2

Compact function is available (PHP 4, PHP 5, PHP 7, PHP 8) Compact - Create an array containing variables and their values. instead of using an array Compact helps because you don’t need to iterate it, I usually use it for singular values, that is to assign a single value whether or not it is provided with an array. I advise you not to use it in vectors with more than one dimension or with a set of keys and values (data). For in these cases even passes the vector on the page or an object in which you intend to send it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.