Variadic/Variable/Keyword Arguments in PHP
I miss being able to just pass in named variables in Python. Well, while PHP isn’t as elegant at that, I’ve decided to use this:
function vargs(&$var, $default) { $var = isset($var) ? $var: $default; } function some_func($args) { extract($args); vargs($first, ''); var_dump($first); } some_func(array('first' => '1st', 'second' => '2nd'));The
first
string will turn into $first
which will then be set to 1st
. If first is missing, then vargs()
will set it to the default you’ve provided. The main downside in PHP is the array() notation and having to use strings, whereas Python will let you name the variable like so:
some_func(first = '1st', second = '2nd')Another way in PHP is to set your functions to their default values, then to run
extract
, which will replace these default values if the variable exists or leave them default otherwise.
function some_func($args) { $these = '1'; $are = '2'; $variables = '3'; extract($args); // Either '1' or the given argument var_dump($these); } // Prints 'one', not '1' some_func(array('these' => 'one'));