Why I have to specify the Class name on a PHP Adapter

50 Views Asked by At

While creating a PHP Adapter, all sources I read uses the following syntax:

class Adapter {
  private $object;

  public function __construct(**OriginalClass** $obj) {
    $this->object = $obj;
  ...

What I don't understand is why I have to state the name of the class in the adapter constructor argument, just before the object itself. Couldn't I just use ... __construct($obj) {, since the object will be already instantiated when passed as an argument?

2

There are 2 best solutions below

0
On BEST ANSWER

The **OriginalClass** part is called type hint that restrict the constructor argument to object of a particular class. So, in your case it is making sure your Adapter class can only be used for a particular class.

0
On

Stating the class name forces the accepted parameter instance.

__construct(OriginalClass $obj)

This forces OriginalClass to be passed. If you pass DifferentClass as a constructor parameter, the code will fail to compile/run.