What is the good example of using 'func_get_arg' in PHP?

后端 未结 7 1194
梦谈多话
梦谈多话 2021-02-07 00:39

I just have found out that there is a function called func_get_arg in PHP which enables developer to use variant style of getting arguments. It seems to be very us

7条回答
  •  旧巷少年郎
    2021-02-07 01:16

    First of all, you are using the term "polymorphism" totally wrong. Polymorphism is a concept in object-oriented programming, and it has nothing to do with variable number of arguments in functions.

    In my experience, all func_get_args allows you to do is add a little syntactic sugar.

    Think of a function that can take any number of integers and return their sum. (I 'm cheating, as this already exists in array_sum. But cheating is good if it keeps the example simple). You could do it this way:

    // you can leave "array" out; I have it because we should be getting one here
    function sum1(array $integers) {
        return array_sum($integers);
    }
    

    Now you would call this like so:

    $sum = sum1(array(1));
    $sum = sum1(array(1, 2, 3, 4));
    

    This isn't very pretty. But we can do better:

    function sum2() {
        $integers = func_get_args();
        return array_sum($integers);
    }
    

    Now you can call it like this:

    $sum = sum2(1);
    $sum = sum2(1, 2, 3, 4);
    

提交回复
热议问题