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 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择