Can you pass more parameters than a function expects?

拈花ヽ惹草 提交于 2019-11-30 23:44:23

问题


If you have two classes extending the same base class, and need to make one of them override a function to take an additional parameter. Is it okay to always pass the additional parameter when calling the function on either class?

A bit of pseudo-code to help demonstrate...

If we have the 3 classes and functions

  • foo::doSomething()
  • foo_subclass_one::doSomething()
  • foo_subclass_two::doSomething($input)

And I have an instance of one of these three, can I call $instance.doSomething($input)

I -think- what happens is that foo and foo_subclass_one would just ignore the additional parameter and foo_subclass_two would make use of it. Is this correct? Is there a better way I can do this if I have a lot of subclasses and really want to avoid touching 10+ files?

Thanks!


回答1:


Yes you can. Gather them with func_get_args()




回答2:


There are two ways to do this:

Extend the methods to use default parameters:

public function doSomething($input=null) {}

Note that you'll need to do this for all instances, even if it isn't used.

In this case, you may want to use the arguments array of the method:

public function doSomething() {
  $args = func_get_args();
  if (isset($args[0])) { $this->doSomethingElse();
}


来源:https://stackoverflow.com/questions/6051309/can-you-pass-more-parameters-than-a-function-expects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!