PHP接口接受接口参数?
我想在PHP中创建一个接口,但我不想对它在一个公共方法中接受的参数类型有太多限制。我不想这么做PHP接口接受接口参数?,php,oop,Php,Oop,我想在PHP中创建一个接口,但我不想对它在一个公共方法中接受的参数类型有太多限制。我不想这么做 interface myInterface { public function a( myClass $a); } 因为我可能不想向它传递myClass的实例。但是,我确实希望确保传递的对象符合某些参数,这可以通过定义接口来实现。所以我想指定使用接口的类,如下所示: <?php interface iA {} interface iB {} interface iC { p
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 ) {}
}
您的概念完全正确。只有一个小错误。类方法的签名必须与接口中指定的签名相同
正如沃尔克所说:
看。通过缩小takes_a()的范围,只允许使用“apple”,您不允许使用其他“iA”,但接口iC要求接受任何iA作为参数沃尔克
记住这一点,请参阅更正的代码:
<?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());
实现接口时,方法的签名必须与接口中的签名相同。(public函数在您的obj类中取a(iA$a);
),但是您可以在这个实例上传递给apple<代码>$o=新obj()$o->takes_a(新苹果())代码>@RaphaelMüller我不明白你在说什么——我知道如何传递苹果对象。将行添加到脚本末尾不会使脚本编译;它仍然抱怨函数签名不匹配。请参阅。通过缩小的范围,将_a()
仅允许“apple”,您不允许其他“iA”,但接口iC要求接受任何iA作为参数。