Testing optional arguments in PHP Testing optional arguments in PHP php php

Testing optional arguments in PHP


possibly not how you wanted to solve your problem (testing somehow optional arguments), but this is how I would implement it:

public function set_value($key, $value){    $this->_values[$key] = $value;    return $this;}public function set_get_value($key, $value, &$previous){    $previous = $this->get_value($key);    $this->_values[$key] = $value;    return $this;}

Use case example:

$obj->set_get_something('some_key', $some_value, $previous) // set AND get    ->do_something_that_uses_some_key()    ->set_something('some_key', $previous) // and reset    ->do_something_that_uses_some_key()    -> ...

Why use another function?

This solution has a few advantages:

  1. the name is more explicit, less confusion for other coders
  2. no hidden side effects
  3. solves your problem with (undefined) variables already having a value
  4. no overhead of calling func_num_args, or some other "meta" function

EDIT: typo in code.

EDIT 2: removed default value of &$previous set_get_value() function (thanks to draevor)


Extracted from the comments / discussion above:

In order to check whether the argument was passed you have 2 options - check the value of the argument against a value (as you've done with null) or check the number of arguments.

If you go with the first option, there's no value that cannot be passed from outside the function, so there will always be a chance for false positives (the same thing that's happening now with null). DaveRandom's example with a random string should be enough for most cases though, but I see it as overkill.

I think the second option is the most clean (fast, readable, etc). As a small improvement over what you've already done with func_get_args, I'd use func_num_args - this way you'll be checking the number of passed arguments, not the argument indices.