所以我知道,如果在这样调用函数时未提供默认值,您可以将函数的参数编码为具有默认值:
我添加了一个如何实现接口的示例:
interface my_interface {
function my_function();
}
class my_class implements my_interface {
# because the interface calls for a function with no options an error would occur
function my_function($arg_one, $arg_two = 'name') {
...
}
}
class another_class implements my_interface {
# this class would have no errors and complies to the implemented interface
# it also can have any number of arguments passed to it
function my_function() {
list($arg_one, $arg_two, $arg_three) = func_get_args();
...
}
}
但是,我喜欢让我的函数调用func_get_args()
方法,这样当在类中使用它们时,我可以从接口实现函数。有没有办法使用该list()
函数,以便我可以为变量分配默认值,或者我是否需要以冗长而丑陋的方式来做?我现在拥有的是:
function my_function() {
list($arg_one, $arg_two) = func_get_args();
if(is_null($arg_two)) $arg_two = 'name';
...
}
我想要的是完成同样事情的东西,但不是那么冗长。也许是这样的,但当然不会标记错误:
function my_function() {
# If $arg_two is not supplied would its default value remain unchanged?
# Thus, would calling the next commented line would be my solution?
# $arg_two = 'name';
list($arg_one, $arg_two = 'name') = func_get_args();
...
}