PHP:我可以声明一个具有可变数量参数的抽象函数吗?
我希望能够在父类中声明一个带有未知数量参数的抽象函数:
abstract function doStuff(...);
然后用一组暗示的参数定义一个实现:
/**
* @param int $userID
* @param int $serviceproviderID
*/
static function doStuff($userID, $serviceproviderID) {}
到目前为止我得到的最好的方法是这样,
abstract function doStuff();
/**
* @param int $userID
* @param int $serviceproviderID
*/
static function doStuff() {
$args = func_get_args();
...
}
但是每次调用函数时,由于提示,我收到一堆“缺少参数”警告。有更好的办法吗?
编辑:问题有误,请不要浪费时间回答。以下是我一直在寻找的内容,它似乎可以在没有警告的情况下工作。
abstract class Parent {
abstract function doStuff();
}
/**
* @param type $arg1
* @param type $arg2
*/
class Child extends Parent {
function doStuff($arg1, $arg2) {
...
}
}
I want to be able to declare an abstract function in an parent class, with an unknown number of arguments:
abstract function doStuff(...);
and then define an implementation with a set of hinted arguments:
/**
* @param int $userID
* @param int $serviceproviderID
*/
static function doStuff($userID, $serviceproviderID) {}
The best approach I've got so far is this,
abstract function doStuff();
/**
* @param int $userID
* @param int $serviceproviderID
*/
static function doStuff() {
$args = func_get_args();
...
}
But every time the function is called, I get a bunch of 'missing argument' warnings because of the hints. Is there a better way?
Edit: The question's wrong, please don't waste your time answering. The following is what I was looking for, and it seems to work without warnings.
abstract class Parent {
abstract function doStuff();
}
/**
* @param type $arg1
* @param type $arg2
*/
class Child extends Parent {
function doStuff($arg1, $arg2) {
...
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 PHP 5.6 及更高版本中,参数列表可能包含
...
标记来表示该函数接受可变数量的参数。您可以将其应用到抽象类,如下所示:
参数将作为数组传递到给定变量中。
In PHP 5.6 and later, argument lists may include the
...
token to denote that the function accepts a variable number of arguments.You can apply this to an abstract class as follows:
The arguments will be passed into the given variable as an array.
根据评论
如果你想传递任意数量的值,请使用数组
你应该避免“未知数量的参数”,因为它使事情变得更加困难,然后是必要的:接口中的方法签名以及抽象方法应该给用户一个提示,如何该方法适用于任何实现。这是一个重要的部分,用户不需要了解任何有关实现细节的信息。但是,当参数的数量随着每次实现而变化时,他必须知道具体方法是如何实现的。
According the comment
If you want to pass an arbitrary number of values, use arrays
You should avoid "unknown number of arguments", because it makes things more difficult, then necessary: method signatures in interfaces as well as abstract methods should give the user a hint, how the method will work with any implementation. Its an important part, that the user shouldn't need to know anything about the implementation details. But when the number of arguments changes with every implementation, he must know, how the concrete methods are implemented.