PHP function overloading

前端 未结 10 896
北恋
北恋 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);
    
    0 讨论(0)
  • 2020-11-22 17:49

    PHP does not support overloading for now. Hope this will be implemented in the other versions like other programming languages.

    Checkout this library, This will allow you to use PHP Overloading in terms of closures. https://github.com/Sahil-Gulati/Overloading

    0 讨论(0)
  • 2020-11-22 17:51

    It may be hackish to some, but I learned this way from how Cakephp does some functions and have adapted it because I like the flexibility it creates

    The idea is you have different type of arguments, arrays, objects etc, then you detect what you were passed and go from there

    function($arg1, $lastname) {
        if(is_array($arg1)){
            $lastname = $arg1['lastname'];
            $firstname = $arg1['firstname'];
        } else {
            $firstname = $arg1;
        }
        ...
    }
    
    0 讨论(0)
  • 2020-11-22 17:55

    In PHP 5.6 you can use the splat operator ... as the last parameter and do away with func_get_args() and func_num_args():

    function example(...$args)
    {
       count($args); // Equivalent to func_num_args()
    }
    
    example(1, 2);
    example(1, 2, 3, 4, 5, 6, 7);
    

    You can use it to unpack arguments as well:

    $args[] = 1;
    $args[] = 2;
    $args[] = 3;
    example(...$args);
    

    Is equivalent to:

    example(1, 2, 3);
    
    0 讨论(0)
提交回复
热议问题