1

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?

1
  • 1
    I was stumbled upon this question ytd too, I think it means to pass an object that implement that specific interface instead of passing the literal interface itself Commented Feb 9, 2016 at 3:47

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.