dongqixuan3112 2018-06-16 15:54
浏览 12

子必需方法可选签名

Is it possible to make a method on a child class of an abstract parent required, yet still allow the method signature to be optional or different from the defined parent method signature?

abstract class Parent
{
    abstract public function foo();
}

class Child extends Parent
{
    public function foo(Request $request) {
        // do something with request
    }
}

I need to be able to enforce that specific methods exist on the child, yet allow the user to pass in whatever they want to that class.

It seems you can't do this with either abstract methods or interfaces, how does one go about getting this done?

  • 写回答

1条回答 默认 最新

  • dougaoxian8922 2018-06-16 16:35
    关注

    You can't use a different number of parameters, or type hinting of a different type, with an abstract class. You'd have to check the parameter to verify it is the object type you expected.

    If you're going to pass multiple arguments to some versions of foo() then it gets more messy. You would have to use something like foo(...$variable) and then check each array position for what that version of foo() expects.

    abstract class Parent
    {
        abstract public function foo($unused);
    }
    
    class Child extends Parent
    {
        public function foo($request) {
            // check type of $request 
            if ('object' != gettype($request) || 'Request' != get_class($request)) {
                 // throw your exception here
            }
    
            // do something with request
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画