作者: | 来源:互联网 | 2023-09-13 12:43
Ijusthavefoundoutthatthereisafunctioncalledfunc_get_arginPHPwhichenablesdeveloperto
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 useful because number of argument can now be arbitrary, but I cannot think of any good example of using it.
我刚刚发现PHP中有一个名为func_get_arg的函数,它允许开发人员使用获取参数的变体样式。它似乎非常有用,因为参数的数量现在可以是任意的,但是我想不出任何使用它的好例子。
What are the some examples of using this function to fully benefit its polymorphic characteristic?
用这个函数来充分利用它的多态特性的例子有哪些?
7 个解决方案
2
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.
在我的经验中,所有func_get_args允许您添加一点语法糖。
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:
考虑一个函数,它可以取任意数量的整数并返回它们的和。(我在作弊,因为这在array_sum中已经存在。但是作弊如果能保持简单的例子就很好)。你可以这样做:
// 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);