2013-10-02 11 views
7

Ho l'interfaccia:PHP - Interfaccia eredità - dichiarazione deve essere compatibile

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

e classi:

class ActiveRecordBase 
{ 
    ... 
} 

class Product extends ActiveRecordBase 
{ 
    ... 
} 

========

ma posso' t fare questo:

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

o questo:

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

ho ottenuto l'errore "dichiarazione deve essere compatibile"

Quindi, c'è un modo per fare questo in PHP?

+1

So che questo è stato inviato a pochi anni fa, ma ora ecco la mia due cents- messaggio Questo errore non fare è con l'ereditarietà dell'interfaccia. Questo errore è dovuto al fatto che PHP non supporta il vero overloading di funzioni/metodi, come in altri linguaggi (ad es. Java, C++) a cui probabilmente sei abituato. – anotheruser1488182

risposta

10

No, un'interfaccia deve essere implementata esattamente. Se si limita l'implementazione a una sottoclasse più specifica, non è la stessa interfaccia/firma. PHP non ha generici o meccanismi simili.

È sempre possibile controllare manualmente nel codice, ovviamente:

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

ma provo a creare un'altra interfaccia, basata su quello. Non implementare, ma ereditare con restrizioni. – violarium

+0

Non importa se estendete o implementate. Non è possibile modificare una dichiarazione dell'interfaccia, punto. Non si può dire Foo implements Bar quando l'implementazione di Bar è molto più ristretta rispetto a quanto specificato da 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()); 
Problemi correlati