需要方法参数的接口

Let's say I have class:

class Foo implements FooInterface{

   private $a=2;

   //implements sum from interface
   public function sum(){
      return $a+$a;
   }
}

Now I have another class:

class Bar{

    private $foo;

    public function __construct($foo){
        $this->foo = $foo;
    }
}

PHP let's us force object type while calling methods:

function abc(Xyz $xyz){}

Does it supports forcing interfaces? Can I force constructor of Bar to accept only objects that implement FooInterface?

Yes. And it works just like you think it does.

class Foo implements FooInterface {}

class Bar{
    public function __construct(FooInterface $foo) {}
}

Also Note:

  • It isn't called "forcing", it's called type-hinting. Here's the Manual Entry
  • Type-hinting works with concrete classes (hint for Foo), classes that extend another class (Foo extends Baz, hinting for Baz will allow for Foo), and interfaces.