【发布时间】:2013-07-22 00:07:35
【问题描述】:
所以我知道,如果在这样调用函数时未提供默认值,您可以将函数的参数编码为具有默认值:
我添加了一个如何实现接口的示例:
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();
...
}
【问题讨论】:
-
我不知道你为什么要这样做,是什么意思,“以便在类中使用它们时我可以从接口实现函数?”。你能说明为什么这很重要吗?
-
我进行了编辑以更好地理解@elclanrs
标签: php list function arguments