开发者

How to tell if optional parameter in PHP method/function was set or not?

开发者 https://www.devze.com 2023-01-11 21:32 出处:网络
Assume I have a method/function with the following signature: foo($bar = 0) Inside foo, how do I tell if $bar was set or not? isset will alway return a TRUE since $bar is assigned 0 in the event no

Assume I have a method/function with the following signature:

foo($bar = 0)

Inside foo, how do I tell if $bar was set or not? isset will alway return a TRUE since $bar is assigned 0 in the event nothing is passed to foo.

Checking for 0 is not an option. I need to know the difference between the parameter explicitly being s开发者_StackOverflow中文版et to 0 or defaulting to 0.


Simply use func_num_args() to specifically check for how many arguments were passed in.

<?php
function foo($bar = 0)
{
    echo "\nNumber of arguments: " . func_num_args();
}

  // Outputs "Number of arguments: 1"
foo(0);

  // Outputs "Number of arguments: 0"
foo();
?>    

Live example


You can use func_get_args. Example:

function foo($optional=null) {
    if (count(func_get_args()) > 0)
        echo "optional given\n";
    else
        echo "optional not given\n";
}

foo(); //optional not given
foo(null); //optional given

Note that the convention used for internal PHP functions is to always give optional arguments a default value and to have them have the same behavior when both argument is not given and its default value is explicitly given. If you ever find otherwise, file a bug report. This let's you do stuff like this without ifs:

function strpos_wrap($haystack, $needle, $offset = 0) {
    return strpos($haystack, $needle, $offset);
}

This convention is more enforced is userland, as the difficulty that led you to this question has shown you. If the convention doesn't suit your needs, at least reconsider your approach. The purpose of func_num_args/func_get_args is mainly to allow variable argument functions.

0

精彩评论

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