开发者

How can I make an optional argument in my custom function in PHP?

开发者 https://www.devze.com 2023-01-19 02:49 出处:网络
For example, here\'s a quick dummy function that sums it up: function dummy_func($optional) { if (!isset($optional)

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 $ou开发者_StackOverflow社区tput;
}

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?


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).


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!
0

精彩评论

暂无评论...
验证码 换一张
取 消