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 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答