tags:

views:

54

answers:

2

For example, here's a quick dummy function that sums it up:

function dummy_func($optional)
{
    if (!isset($optional)
    {
        $optional = "World!";
    }
    $output = "Hello " . $optional;
    return $output;
}

However, if I run this, I get an E_WARNING for a missing argument. How can I set it up so it doesn't flag an error?

+6  A: 

Optional arguments need to be given a default value. Instead of checking isset on the argument, just give it the value you want it to have if not given:

function dummy_func($optional = "World!")
{
    $output = "Hello " . $optional;
    return $output;
}

See the page on Function arguments in the manual (particularly the Default argument values section).

Daniel Vandersluis
Thank you! This worked perfectly.
Rob
+1  A: 

You can do that by making $optional argument take default value of "World!":

function dummy_func($optional="World!")
{
    $output = "Hello " . $optional;
    return $output;
}

Now when calling the function if you don't provide any argument, $optional will take the default value but if you pass an argument, $optional will take the value passed.

Example:

echo dummy_func();      // makes use of default value...prints Hello World!
echo dummy_func('foo!'); // makes use of argument passed...prints Hello foo!
codaddict
@Downvoter: Care to explain ?
codaddict
I would like to know why his was downvoted, as well. I upvoted it, because it works and is actually the same as the accepted answer, I just couldn't accept both.
Rob