Type hinting means to define which class object we want to receive exactly as a parameter in a constructor
class BLock { }
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 $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 = new Chest(new Block);
$chest->open();
$chest->close();
In this example
Chest
class constructor waits to receive
Lock
class object.
If we pass any other class object, we will get an error like the following:
Fatal error:
Uncaught TypeError: Argument 1 passed to Chest::__construct() must be an instance of Lock, instance of BLock given