0

First of all, I can't recall the name of this process, but it looks something like this:

function test($alter = FALSE){
    //do stuff
    return $alter;
}

Making $alter = FALSE right in the function declaration

What is that called? How does this work? What happens in the following circumstances?

$result = test();

$result = test(TRUE);

Bobby S
  • 4,006
  • 9
  • 42
  • 61
  • You could always test it. If you don't already, you should figure out how to get access to php [on the command line](http://www.php.net/manual/en/features.commandline.usage.php) so you can experiment with things like this. – grossvogel Nov 13 '12 at 23:31
  • I was more curious in what it was called. Overloading I believe is the answer I was looking for. – Bobby S Nov 13 '12 at 23:55
  • [Overloading](http://en.wikipedia.org/wiki/Function_overloading) is something different, but default parameters can be hacked to achieve some of the same effects. In overloading, you define multiple methods with the same name, but with different [signatures](http://en.wikipedia.org/wiki/Method_signature), and the compiler chooses which one to apply based on what you pass in and expect out. – grossvogel Nov 14 '12 at 00:58

4 Answers4

4

FALSE is defined as the default value if no other value is passed.

In the case of you examples the results (in order) would be:

FALSE
TRUE
Mike Brant
  • 70,514
  • 10
  • 99
  • 103
  • +1 See the section 'Default argument values' on [this man page](http://php.net/manual/en/functions.arguments.php) – grossvogel Nov 13 '12 at 23:27
1

FALSE defined in method header is the default value (if nothing is added to parameter while calling) - test() otherwise it behaves like a normal parameter.. so if you call test(TRUE) value will be TRUE

mychalvlcek
  • 3,956
  • 1
  • 19
  • 34
1

Nothing to add except: The term that you probably might be remembering is "function overloading" but this isn't a real embodiment of this (it's just PHP's "default parameter" is perhaps similar)

conners
  • 1,420
  • 4
  • 18
  • 28
  • http://php.net/manual/en/functions.arguments.php calls it "default values for scalar arguments" (see example 3) – conners Nov 13 '12 at 23:35
1
"<?php
echo"welcome";
function a($b=false){
echo"<br /> b: ".$b;
}


a(true);
a();
a("some text");
a(false);

?> result :
welcome
b: 1
b:
b: some text
b:
"

it seems that if its false/null/empty it does not print anything.. and what ever you pass to that method string/boolean it does print as long as not null/empty.