PHP function overloading

前端 未结 10 997
北恋
北恋 2020-11-22 17:24

Coming from C++ background ;)
How can I overload PHP functions?

One function definition if there are any arguments, and another if there are no arguments? Is it

10条回答
  •  长情又很酷
    2020-11-22 17:48

    You cannot overload PHP functions. Function signatures are based only on their names and do not include argument lists, so you cannot have two functions with the same name. Class method overloading is different in PHP than in many other languages. PHP uses the same word but it describes a different pattern.

    You can, however, declare a variadic function that takes in a variable number of arguments. You would use func_num_args() and func_get_arg() to get the arguments passed, and use them normally.

    For example:

    function myFunc() {
        for ($i = 0; $i < func_num_args(); $i++) {
            printf("Argument %d: %s\n", $i, func_get_arg($i));
        }
    }
    
    /*
    Argument 0: a
    Argument 1: 2
    Argument 2: 3.5
    */
    myFunc('a', 2, 3.5);
    

提交回复
热议问题