doulu8415 2017-03-28 08:59
浏览 50
已采纳

使用自定义对象创建界面功能

Is there an oppotunity to create an interface function in PHP, where a parameter requires to be an object, but not specified, what object it has to be?

Now my code looks like this:

interface Container {
    public static function add(\Employee $element);
}

Right now I can just implement the function with a parameter, which requires an instance from "Employee". When I now implement it in a class it looks like this:

class EmployeeContainer implements Container {
    public static function add(\Employee $element) {
        $pnr = $element->getPNR();
    }
}

When I create another class, that implements Container and set the required Object for example to Trainee, the PHP compiler throws an error:

class TraineeContainer implements Container {
    public static function add(\Trainee $element) {
        $pnr = $element->getPNR();
    }
}

Fatal error: Declaration of TraineeContainer::add($element) must be compatible with Container::add(Employee $element)

Is there a way to set in the interface the required object to a custom object?

Why I want this?

Many IDE's supporting this form of instance description to suggest methods based on an object.

  • 写回答

2条回答 默认 最新

  • doutangdan3588 2017-03-28 09:26
    关注

    Custome object argument is not possible in interface but you can achieve it in other way.

    create a common base class

    class SomeBaseClass{
    
    }
    

    extend your classes

    class Employee extends SomeBaseClass{
    
    }
    
    class Trainee extends SomeBaseClass{
    
    }
    

    then use SomeBaseClass as argument in your interface

    interface Container {
        public static function add(SomeBaseClass $element);
    }
    
    class EmployeeContainer implements Container {
        public static function add(SomeBaseClass $element) {
            $pnr = $element->getPNR();
        }
    }
    
    class TraineeContainer implements Container {
        public static function add(SomeBaseClass $element) {
            $pnr = $element->getPNR();
        }
    }
    

    It seems you have getPNR common function so you can create an abstract class or interface and use that in your child classes.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路