-1

(Perhaps this question has already been asked before, but I can't find it.)

What happens if you have an argument with default value preceding an argument without default value in PHP? Just like this:

function myfunction($foo = 12, $bar) {
    ...
}
  • Does PHP give errors and if yes, on which error reporting level?
  • What happens when you call myfunction("hello") with only one argument?
MC Emperor
  • 22,334
  • 15
  • 80
  • 130

1 Answers1

1

Yes, it will output a warning, not an error, namely:

Warning: Missing argument 2 in call to myfunction() in FILE on line LINENO

If you call myfunction("hello"), $bar is undefined, so it will either be an empty string or NULL, and $foo = "hello". It will only raise a warning though, so your script will still execute.

Why don't you just switch the order of the parameters?

Edit: Here is a good explanation of why it is not possible to overload standalone functions in PHP: PHP function overloading

Community
  • 1
  • 1
nickb
  • 59,313
  • 13
  • 108
  • 143
  • 1
    What you're referring to is function overloading, no? If that's the case, you can overload methods in a class, but not standalone functions, like so: http://www.php.net/manual/en/language.oop5.overloading.php – nickb Nov 02 '11 at 13:02
  • I don't like the argument names to be misleading. Say I have `function cr_name($firstname, $infix, $lastname)`. It would be weird to mix up the order of arguments. For example, I don't like to input `"Leonardo", "Caprio", "di"`. Instead, I want to input it as the human logical order (Leonardo, di, Caprio). But if a name has no infix (e.g. George Clooney), I prefer to input it as `"George", "Clooney"`, skipping the `$infix` argument. In Java, you *can* achieve that, defining 2 methods with the same name. It's called overloading. – MC Emperor Nov 02 '11 at 13:05
  • Thank you, @nickb, I got it. I have created the following code, which appears to work: `public function createname() { $this->__call(__FUNCTION__, func_get_args()); } public function __call($name, $arguments) { switch ($name) { case "createname": switch (count($arguments)) { case 2: $this->firstname = $arguments[0]; $this->infix = ""; $this->lastname = $arguments[1]; break; case 3: $this->firstname = $arguments[0]; $this->infix = $arguments[1]; $this->lastname = $arguments[2]; break; } break; } }` Notice: the empty function `createname()` is only for the editor to recognise my function. – MC Emperor Nov 02 '11 at 13:39