PHP function overloading

前端 未结 10 884
北恋
北恋 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: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);
    

提交回复
热议问题