PHP: Passing Interface as Parameter

浪子不回头ぞ 提交于 2020-01-30 02:49:29

问题


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


回答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




回答2:


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.



来源:https://stackoverflow.com/questions/7705348/php-passing-interface-as-parameter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!