Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge two class in PHP?

Tags:

php

class

So that the final class have all member variables/methods in both class

Is there an easy way to go?

like image 885
user198729 Avatar asked Mar 03 '10 20:03

user198729


1 Answers

You should encapsulate the both classes in a containing class, and provide a relevant interface (such as setters/getters for private variables

class YourFirstClass {
   public $variable;
   private $_variable2;
   public function setVariable2($a) {
       $this->_variable2 = $a;
   }
}

class YourSecondClass {
   public $variable;
   private $_variable2;
   public function setVariable2($a) {
       $this->_variable2 = $a;
   }
}

class ContaingClass {
   private $_first;
   private $_second;
   public function __construct(YourFirstClass $first, YourSecondClass $second) {
       $this->_first = $first;
       $this->_second = $second;
   }
   public function doSomething($aa) {
       $this->_first->setVariable2($aa);
   }
}

Research (google): "composition over inheritance"

Footnote: sorry for non-creative variable names..

like image 51
chelmertz Avatar answered Sep 17 '22 05:09

chelmertz