2013-10-02 21 views
7

Mam interfejs:PHP - Interfejs dziedziczenia - deklaracja musi być zgodny

interface AbstractMapper 
{ 
    public function objectToArray(ActiveRecordBase $object); 
} 

i klas:

class ActiveRecordBase 
{ 
    ... 
} 

class Product extends ActiveRecordBase 
{ 
    ... 
} 

========

ale mogę” t wykonaj następujące czynności:

interface ExactMapper implements AbstractMapper 
{ 
    public function objectToArray(Product $object); 
} 

lub inna:

interface ExactMapper extends AbstractMapper 
{ 
    public function objectToArray(Product $object); 
} 

mam błąd „deklaracja musi być zgodna

Więc, czy jest jakiś sposób, aby to zrobić w PHP?

+1

Znam ten został opublikowany kilka lat temu, ale teraz oto moje dwa centa wiadomość Ten błąd nie zrobić, to z dziedziczeniem interfejsu. Ten błąd wynika z tego, że PHP nie obsługuje przeciążania prawdziwych funkcji/metod, tak jak w innych językach (np. Java, C++), do których prawdopodobnie przywykłeś. – anotheruser1488182

Odpowiedz

10

Nie, interfejs musi być zaimplementowany dokładnie. Jeśli ograniczysz implementację do bardziej określonej podklasy, nie będzie to ten sam interfejs/podpis. PHP nie ma generycznych ani podobnych mechanizmów.

Zawsze można ręcznie sprawdzić w kodzie, oczywiście:

if (!($object instanceof Product)) { 
    throw new InvalidArgumentException; 
} 
+0

ale staram się stworzyć inny interfejs, oparty na tym. Nie implementuj, ale dziedzicz z ograniczeniami. – violarium

+0

Nie ma znaczenia, czy rozszerzasz, czy wdrażasz. Nie można zmienić deklaracji interfejsu, kropka. Nie możesz powiedzieć, że Foo implementuje pasek, kiedy implementacja Baru jest znacznie bardziej ograniczona niż to, co określił Foo. – deceze

-3
interface iInvokable { 
    function __invoke($arg = null); 
} 

interface iResponder extends iInvokable { 
    /** Bind next responder */ 
    function then(iInvokable $responder); 
} 

class Responder implements iResponder { 

    function __invoke($arg = null) 
    { 
     // TODO: Implement __invoke() method. 
    } 

    /** Bind next responder */ 
    function then(iInvokable $responder) 
    { 
     // TODO: Implement then() method. 
    } 
} 

class OtherResponder implements iResponder { 

    function __invoke($arg = null) 
    { 
     // TODO: Implement __invoke() method. 
    } 

    /** Bind next responder */ 
    function then(iInvokable $responder) 
    { 
     // TODO: Implement then() method. 
    } 
} 

class Invokable implements iInvokable { 

    function __invoke($arg = null) 
    { 
     // TODO: Implement __invoke() method. 
    } 
} 

$responder = new Responder(); 
$responder->then(new OtherResponder()); 
$responder->then(new Invokable()); 
Powiązane problemy