2013-10-02 13 views
7

Tôi có giao diện:PHP - Giao diện thừa kế - Tờ khai phải phù hợp

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

Và lớp:

class ActiveRecordBase 
{ 
    ... 
} 

class Product extends ActiveRecordBase 
{ 
    ... 
} 

========

Nhưng tôi có thể' t làm điều này:

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

hoặc điều này:

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

Tôi đã có lỗi "khai phải phù hợp"

Vì vậy, có một cách để làm điều này trong PHP?

+1

Tôi biết điều này đã được đăng cách đây vài năm nay nhưng đây là hai cents- nhắn Lỗi này tôi không làm là với giao diện kế thừa. Lỗi này là do PHP không hỗ trợ quá tải đúng chức năng/phương thức, như trong các ngôn ngữ khác (ví dụ: Java, C++) mà bạn có thể đã từng sử dụng. – anotheruser1488182

Trả lời

10

Không, giao diện phải được triển khai chính xác. Nếu bạn hạn chế việc triển khai vào một lớp con cụ thể hơn, nó không phải là cùng một giao diện/chữ ký. PHP không có generics hoặc các cơ chế tương tự.

Bạn luôn có thể tự kiểm tra trong mã, tất nhiên:

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

nhưng tôi thử tạo một giao diện khác, dựa trên đó. Không triển khai, nhưng kế thừa với hạn chế. – violarium

+0

Nó không thực sự quan trọng cho dù bạn mở rộng hoặc thực hiện. Bạn không thể thay đổi một khai báo giao diện, thời gian. Bạn không thể nói Foo thực hiện Bar khi việc thực hiện của Bar bị hạn chế nhiều hơn những gì Foo đã chỉ định. – 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()); 
Các vấn đề liên quan