douying0108 2012-06-22 14:28
浏览 31
已采纳

如何根据对象的真实类名运行代码?

I am going through a list of objects, all with the same parent class but they could be instances from one of many sub classes. Depending on the true type of the object I want to perform slightly different operations.

How can I run different blocks of code based on the object types?

In Java I would overload a processing function with each type I wanted to work with, but PHP doesn't allow this.

Background: To Gordon's comment.

We are building forms from a group of objects. A super class Component that is extended to represent specific types of form elements. TextInput extends Component and the Component has the ability to hold other Components. We don't want them to be responsible for their actual representation.

We are working to build HTML right now, but we might potentially want to use them to build .PDFs or other formats.

So we have code that goes through the Components, and recursively through the Components it contains. Depending on the type of the Component, we need to create different output.

  • 写回答

3条回答 默认 最新

  • donte1234567 2012-06-22 14:33
    关注

    Use

    if($myobject instanceof class1){
    }elseif($myobject instanceof class1){
    }
    

    Or

    switch(get_class($myobject)){
        case 'class1':
           break;
        case 'class2':
           break;
    }
    

    Also, make sur you don't break the Open/Closed principle. If you put that portion of code in a class and not in a specific portion of a controller, you end up breaking an important reusability feature of your code:

    Open / Closed Principle

    Have you never done a plug-in system? If you did, i’m sure you didn’t ask your users to hardcode a loading line in the code to handle that plug-in right?

    Normaly speaking, you’d want your classes to be extendable without needing to change the parent. Extension should be an open principle where adding more code should be as easy as extending but you should never have to modify the parent class.

    Thus addind a switch inside the parent or inside another class to handle all possible versions of that class breaks the open principle, because users then have to change the class to add more features...

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

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料