Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I would suggest using the associative array to pass named parameters, but keep them in the array without extracting them.</p> <pre><code>function myFunc(array $args) { echo "Hi, " . $args['name']; // etc } </code></pre> <p>There's a couple of reasons for this. Looking at that function, you can quite clearly see that I'm referring to one of the arguments passed into the function. If you extract them, and don't notice the <code>extract()</code> you (or the next guy) will be there scratching your head wondering where this "<code>$name</code>" variable came from. Even if you <em>do</em> know you're extracting the arguments to local variables, it's still a guessing game to a certain degree.</p> <p>Secondly, it ensures that other code doesn't overwrite the args. You may have written your function expecting only to have arguments named <code>$foo</code> and <code>$bar</code>, so in your other code, you define <code>$baz = 8;</code>, for example. Later on, you might want to expand your function to take a new parameter called "baz" but forget to change your other variables, so no matter what gets passed in the arguments, <code>$baz</code> will always be set to 8.</p> <p>There are some benefits to using the array too (these apply equally to the methods of extracting or leaving in the array): you can set up a variable at the top of each function called <code>$defaults</code>:</p> <pre><code>function myFunc (array $args) { $default = array( "name" =&gt; "John Doe", "age" =&gt; "30" ); // overwrite all the defaults with the arguments $args = array_merge($defaults, $args); // you *could* extract($args) here if you want echo "Name: " . $args['name'] . ", Age: " . $args['age']; } myFunc(array("age" =&gt; 25)); // "Name: John Doe, Age: 25" </code></pre> <p>You could even remove all items from <code>$args</code> which don't have a corresponding <code>$default</code> value. This way you know exactly which variables you have.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload