Pass interface as a type-hint in constructor or method parameter.

Dev Singh. September 21, 2019 Comments

The concept of passing interface typehint as constructor or method parameter means you can only pass the object in the parameter who has inherit the same interface.

Still you didn't understand try to understand the same from the below code.

interface abcInterface {

    public function show();
}

/**
 * It inherit the abcInterface
 */
class classOne implements abcInterface {

    public function show() {
        echo __CLASS__;
    }

}

/**
 * Didn't inherit the abcIterface
 */
class classTwo {

    public function show() {
        echo __CLASS__;
    }

}

class demoClass {

    function __construct(abcInterface $pclass) {
        $pclass->show();
    }

}

$a = new demoClass(new classOne());


/**
 * This will produce an error bcoz demoClass constructor has interface typehint and 
 * classTwo has not inherit the abcInterface.
 */
$b = new demoClass(new classTwo());

 

error : 

classOne
Catchable fatal error: Argument 1 passed to demoClass::__construct() must implement interface abcInterface, instance of classTwo given, called in ....

  • PHP
  • parameters
  • interface
  • type-hinting