code_junkie

Can I extend a class using more than 1 class in PHP?

Nov 12th, 2011
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. class B {
  2. public function method_from_b($s) {
  3. echo $s;
  4. }
  5. }
  6.  
  7. class C {
  8. public function method_from_c($s) {
  9. echo $s;
  10. }
  11. }
  12.  
  13. class A extends B
  14. {
  15. private $c;
  16.  
  17. public function __construct()
  18. {
  19. $this->c = new C;
  20. }
  21.  
  22. // fake "extends C" using magic function
  23. public function __call($method, $args)
  24. {
  25. $this->c->$method($args[0]);
  26. }
  27. }
  28.  
  29.  
  30. $a = new A;
  31. $a->method_from_b("abc");
  32. $a->method_from_c("def");
  33.  
  34. class Extendable{
  35. private $extender=array();
  36.  
  37. public function addExtender(Extender $obj){
  38. $this->extenders[] = $obj;
  39. $obj->setExtendee($this);
  40. }
  41.  
  42. public function __call($name, $params){
  43. foreach($this->extenders as $extender){
  44. //do reflection to see if extender has this method with this argument count
  45. if (method_exists($extender, $name)){
  46. return call_user_func_array(array($extender, $name), $params);
  47. }
  48. }
  49. }
  50. }
  51.  
  52.  
  53. $foo = new Extendable();
  54. $foo->addExtender(new OtherClass());
  55. $foo->other_class_method();
  56.  
  57. // this is NOT allowed (for all you google speeders)
  58. Matron extends Nurse, HumanEntity
  59.  
  60. Matron extends Nurse
  61. Consultant extends Doctor
  62.  
  63. Nurse extends HumanEntity
  64. Doctor extends HumanEntity
  65.  
  66. HumanEntity extends DatabaseTable
  67. DatabaseTable extends AbstractTable
  68.  
  69. class C
  70. {
  71. private $a, $b;
  72.  
  73. public function __construct($x, $y)
  74. {
  75. $this->a = new A(42, $x);
  76. $this->b = new B($y);
  77. }
  78.  
  79. protected function DoSomething()
  80. {
  81. $this->a->Act();
  82. $this->b->Do();
  83. }
  84. }
Add Comment
Please, Sign In to add comment