Dependency injection is a technique when we pass one class object to another class constructor:
class Lock {
private $isLocked;
public function __construct() {
}
public function lock() {
$this->isLocked = true;
}
public function unLock() {
$this->isLocked = false;
}
public function isLocked() {
return $this->isLocked;
}
}
class Chest {
private $lock;
public function __construct($lock) {
$this->lock = $lock;
}
public function close() {
$this->lock->lock();
echo 'Closed' . PHP_EOL;
}
public function open() {
if ($this->lock->isLocked()) {
$this->lock->unLock();
}
echo 'Opened' . PHP_EOL;
}
public function isClosed() {
return $this->lock->isLocked();
}
}
$chest = new Chest(new Lock);
$chest->open();
$chest->close();