I have the following class
class InterfaceImplementation{
public function __construct(ServiceInterface $oService){
$this->oService = $oService;
}
}
When I create the class object
$obj = new InterfaceImplementation();
How to pass the interface instance?And is this the correct way to code?
Any object that will implement ServiceInterface
can be used and pass to the constructor. You have to create an instance of the class, but in InterfaceImplementation
you will use the interface API (methods declarated in the interface), not the methods from the particular class.
Before you can create a new InterfaceImplementation
, you need to have a valid ServiceInterface
object. Once you have the service object you can pass it while creating InterfaceImplementation
$service = new ServiceInterface(); // make sure its a valid object
$implementation = new InterfaceImplementation($service);
Pro tip: Look up a dependency injection container. It will make your life so much easier.