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 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示