3

In .NET I have done that I passed Interfaces as parameters in class methods. I want to know is it possible in PHP?

My scnerio is that I have a class dealing with mqin system functionality. Now I want to integrate Notification system with it. I want to keep notification system separate since it is not the main part of the system plus I can use it somewhere else. If I have the following structure:

Interface INotification
{
  public set()
  public send()
}

And then I do:

class MyClass
{
   public setNotifier(INotification $notifier)
  {
  }
}

So Is it possible that I can access set() and send() here after implementing them in a class? I want to know how this C# Example work that they set parameters of an Interface type.

Thanks

3
  • 2
    You only forgot the function keyword everywhere and semicolons in the interface declaration. But that's how it works. Commented Oct 9, 2011 at 17:56
  • This counts for most parts of php: just do it. Just call the method on your parameter, it will work. Commented Oct 9, 2011 at 17:56
  • (reference) php.net/manual/en/language.oop5.typehinting.php Commented Oct 9, 2011 at 18:00

2 Answers 2

1

Yes, it is possible, pretty much as you wrote. Example of such interface: http://api.nette.org/2.0/source-Http.IResponse.php.html#18 and example of such parameter: http://api.nette.org/2.0/source-Http.Context.php.html#32

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

2 Comments

Awesome. A pretty much clear explaination how OOPS complex feature gonna work. Infact other things are also well explained. Thanks a bunch!
What advantage do I get passing Interface as parameters instead of object of type Class? see the code. pastebin.ca/2088573
0

Yes, you can do as you coded. You can find more information and examples on php.net.

Note that specifying the type in the method parameter (type hinting) is allowed (PHP >= 5), but not required.

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.