的PHP OOP聲明我有以下OOP結構:接口實現兼容性
<?php
interface AnimalInterface
{
public function getName();
}
class Dog implements AnimalInterface
{
public function getName() {
return 'dog';
}
public function makeFriends()
{
echo 'I have friends now :)';
}
}
class Cat implements AnimalInterface
{
public function getName() {
return 'cat';
}
public function hateFriends()
{
echo 'I cant make friends :(';
}
}
interface AnimalDoInterface
{
public function makeFriend(AnimalInterface $animal);
}
class DogFriend implements AnimalDoInterface
{
public function makeFriend(Dog $dog)
{
$dog->makeFriends();
}
}
class CatFriend implements AnimalDoInterface
{
public function makeFriend(Cat $cat)
{
$cat->hateFriends();
}
}
現在PHP對Object Interfaces手冊說:
The class implementing the interface must use the exact same method signatures as are defined in the interface. Not doing so will result in a fatal error.
爲什麼會出現這種情況?我完全誤解了界面嗎?當然,我應該能夠聲明AnimalDoInterface::makeFriend
任何接口或接口的實現?在這種情況下,它應該在技術上與Cat
implements AnimalInterface
兼容,這正是它期望的。
無論我是否讓我的OOP出錯,是否有一種方法可以在PHP中實現這一點?
所以看來我還不夠清楚,我的不好。然而,基本上我試圖實現的是讓AnimalDoInterface
的實現比接口說的更具限制性。所以在這種情況下,我想DogFriend::makeFriend
只允許Dog
類作爲它的參數,在我看來應該是可以接受的,因爲它實現了AnimalInterface
,並且CatFriend
允許Cat
類,這也是同樣的事情。
編輯:修正了類,還增加了我試圖實現的內容。
編輯2:此刻
所以,我必須實現它的方法是如下:
class DogFriend implements AnimalDoInterface
{
public function makeFriend(AnimalInterface $dog)
{
if(!($dog instanceof Dog)) {
throw new \Exception('$dog must be of Dog type');
}
$dog->makeFriends();
}
}
class CatFriend implements AnimalDoInterface
{
public function makeFriend(AnimalInterface $cat)
{
if(!($dog instanceof Cat)) {
throw new \Exception('$dog must be of Cat type');
}
$cat->hateFriends();
}
}
我想有以避免類此額外的檢查類型。
我不認爲我跟着你說的任何話。什麼是實際問題?「方法簽名」是指方法名稱,參數(帶有類型提示),可見性(公共/私人)以及它是否是靜態的。 –
不完全清楚你在問什麼。你是否嘗試運行上面的代碼?它會與錯誤'致命錯誤:類狗包含1抽象方法,因此必須聲明爲抽象或實現其餘方法(AnimalInterface :: getAnimalName)' –
實施'AnimalInterface'類沒有方法'getAnimalName()'哪是抽象的。並且必須使用。請記住,所有接口方法本身都是抽象的,並且必須在類中實現。 –