2 min readFeb 20, 2022
class Lamp {
//TRUE = on, FALSE = Off
protected bool $currentState = FALSE;
public function turnOn() {
$this->currentState = TRUE;
}
public function turnOff() {
$this->currentState = FALSE;
}
public function getState() {
return $this->currentState;
}
public function getStateString(): string {
if ($this->currentState) {
return 'On';
} else {
return 'Off';
}
}
}
class Button {
protected Lamp $lamp;
public function __construct(Lamp $l) {
$this->lamp = $l;
}
public function On() {
$this->lamp->turnOn();
}
public function Off() {
$this->lamp->turnOff();
}
}
$l = new Lamp();
$b = new Button($l);
echo $l->getStateString(); //Off
$b->On();
echo $l->getStateString(); //On
You can see one class depends one another. How we can fix this is with an example below.
interface DeviceInterface {
public function turnOn();
public function turnOff();
}
class Lamp implements DeviceInterface {
//TRUE = on, FALSE = Off
protected bool $currentState = FALSE;
public function turnOn() {
$this->currentState = TRUE;
}
public function turnOff() {
$this->currentState = FALSE;
}
public function getState() {
return $this->currentState;
}
public function getStateString(): string {
if ($this->currentState) {
return 'On';
} else {
return 'Off';
}
}
}
interface ButtonInterface {
public function On();
public function Off();
}
class Button implements ButtonInterface {
protected DeviceInterface $di;
public function __construct(DeviceInterface $di) {
$this->di = $di;
}
public function On() {
$this->di->turnOn();
}
public function Off() {
$this->di->turnOff();
}
}
$l = new Lamp();
$b = new Button($l);
echo $l->getStateString(); //Off
$b->On();
echo $l->getStateString(); //On
What we done here. We create 2 interfaces and implement 2 other classes from them, so we can change Button class or Lamp class. but whatever we created instead of those will be work just like others . Why? Just because all of them derived from one interface. methods may do different jobs but they should have same properties and method names. Hope i can explain this.