PHP接口接受接口参数


PHP interface accepts interface argument?

我想在PHP中创建一个接口,但我不希望它对在一个公共方法中接受的参数类型有太多限制。我不想做

interface myInterface {
    public function a( myClass $a);
}

因为我可能不想给它传递一个myClass的实例。但是,我确实想确保传递的对象符合某些参数,这可以通过定义接口来实现。所以我想指定使用接口的类,像这样:

<?php
interface iA {}
interface iB {}
interface iC {
    public function takes_a( iA $a );
    public function takes_b( iB $b );
}
class apple implements iA {}
class bananna implements iB {}
class obj implements iC {
    public function takes_a( apple $a ) {}
    public function takes_b( bananna $b ) {}
}

但是,我得到错误PHP Fatal error: Declaration of obj::takes_a() must be compatible with iC::takes_a(iA $a) on line 15

是否有办法确保一个参数只接受一个特定接口的类?或者我想太多了?

你的想法完全正确。只有一个小毛病。您的类方法必须具有与接口中指定的签名相同的签名。

正如VolkerK所说:

看到维基百科。通过缩小takes_a()只允许"apple",你就不允许其他"iA",但是接口iC要求接受任何iA作为参数。——VolkerK

考虑到这一点,请参阅更正后的代码:
<?php
interface iA {
    function printtest();
}
interface iB {
    function play();
}
//since an interface only have public methods you shouldn't use the verb public
interface iC {
    function takes_a( iA $a );
    function takes_b( iB $b );
}
class apple implements iA {
    public function printtest()
    {
        echo "print apple";
    }
}
class bananna implements iB {
    public function play()
    {
        echo "play banana";
    }
}
//the signatures of the functions which implement your interface must be the same as specified in your interface
class obj implements iC {
    public function takes_a( iA $a ) {
        $a->printtest();
    }
    public function takes_b( iB $b ) {
        $b->play();
    }
}
$o = new obj();
$o->takes_a(new apple());
$o->takes_b(new bananna());