duanshai4484 2015-09-03 18:53
浏览 17
已采纳

使用不同的共享方法和属性扩展PHP类

I have the following three objects which includes the following methods and properties:

$obj1
 - $prop1
 - $prop2
 - $prop3
 - $prop4
 - method1()
 - method2()
 - method3()
 - method4()

$obj2
 - $prop2
 - $prop3
 - $prop4
 - $prop5
 - method2()
 - method3()
 - method4()
 - method5()

$obj3
 - $prop1
 - $prop3
 - $prop4
 - $prop5
 - method1()
 - method3()
 - method4()
 - method5()

All properties and methods of a given name utilize identical script to create them.

One possible script to create these objects is as follows:

class class1 { 
  var $prop1=123, $prop2=array(), $prop3, $prop4;
  public method method1($x) {echo('hello '.$x;}
  public method method2($x) {echo('goodby '.$x;}
  public method method3($x) {echo('hey '.$x;}
  public method method4($x) {echo('seeya '.$x;}
}

class class2 { 
  var $prop2=array(), $prop3, $prop4, $prop5=555,;
  public method method2($x) {echo('goodby '.$x;}
  public method method3($x) {echo('hey '.$x;}
  public method method4($x) {echo('seeya '.$x;}
  public method method5($x) {echo('latter '.$x;}
}

class class3 { 
  var $prop1=123,  $prop3, $prop4, $prop5=555,;
  public method method1($x) {echo('hello '.$x;}
  public method method3($x) {echo('hey '.$x;}
  public method method4($x) {echo('seeya '.$x;}
  public method method5($x) {echo('latter '.$x;}
}

How can I create these three objects without duplicating the script used to create the properties and methods?

  • 写回答

2条回答 默认 最新

  • doushu2699 2015-09-03 20:03
    关注

    Untested and not positive it will work. Also, concerned it will be difficult to maintain.

    trait trait_1{
      var $prop1=123;
      public method method1($x) {echo('hello '.$x;}
    }
    trait trait_2{
      $prop2=array();
      public method method2($x) {echo('goodby '.$x;}
    }
    trait trait_5{
       $prop5=555;
      public method method5($x) {echo('latter '.$x;}
    }
    
    trait trait_3_4{
      var $prop3, $prop4;
      public method method3($x) {echo('hey '.$x;}
      public method method4($x) {echo('seeya '.$x;}
    }
    
    class class1 { 
      use trait_1, trait_2,  trait_3_4;
    }
    class class2 { 
      use trait_2,  trait_3_4, trait_5;
    }
    class class3 { 
      use trait_1,  trait_3_4, trait_5;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥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,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?