2016-05-29 211 views
0

我有以下情形:PHP抽象類和接口

abstract class Contractor { 
    // Generic contractor methods...   
    } 

    abstract class PrivatePerson extends Contractor { 
    // Adds methods specific to private contractors 
    } 

    abstract class Company extends Contractor { 
    // Adds methods specific to Company contractors 
    } 

    class CustomerPrivate extends PrivatePerson { 
    // Customers that are contractors, but physical persons 
    } 

    class CustomerCompany extends Company { 
    // Customers that are contractors, but companies 
    } 

並與供應商和經銷商,它可以是私人或者公司發生同樣的情況。現在的問題是:如何強制CustomerPrivate和CustomerCompany類的對象同時是Customer類(我尚未定義),供應商和經銷商也是如此。在這種情況下使用接口是一種很好的做法?

interface Customer { 
    } 

    class PrivateCustomer extends PrivatePerson implements Customer { 
    // Customers that are physical persons, but are CUSTOMERS! 
    } 

感謝您的任何建議!

回答

0

方法1

class CustomerPrivate extends PrivatePerson 
{ 
    public function __construct() 
    { 
     if($this instanceof Customer) 
     { 
      //CODE 
     } 
     else 
     { 
      throw new \Exception("YOU ERROR MESSAGE", 1); 
      # code... 
     } 
    } 
} 

方法2

$obj = new CustomerPrivate(); 

if ($obj instanceof Customer) 
{ 
    //CODE 
} 
else 
{ 
    # code... 
} 

您可以爲任何類做到這一點,你要

EDITED

是你可以在你的接口,如您發佈

interface Customer 
{ 
} 

class PrivateCustomer extends PrivatePerson implements Customer 
{ 
    // Customers that are physical persons, but are CUSTOMERS! 
} 

OR

您可以使用的特性。 的特性是非常靈活的,但他們只在PHP 5.4支持或更高

trait Customer 
{ 

} 

class PrivateCustomer extends PrivatePerson 
{ 
    use Customer; //trait customer 
    use OtherTrait; 

    // Customers that are physical persons, but are CUSTOMERS! 
} 

EDIT 2

有不同的算法來解決你的問題取決於您的方案。我無法想象整個場景,但從你的問題。你想要在兩種不同的樹(人和公司)中有共同的客戶類型,在這種情況下,線性層次結構是一個問題,所以我可能會使用類似這樣的東西。

abstract class Contractor 
{ 
    public function isCustomer() 
    { 
     return FALSE; 
    } 
} 


trait Customer 
{ 
    public function isCustomer() 
    { 
     return TRUE; 
    } 
} 

class CustomerCompany extends Company 
{ 
    \\use Customer; 

    public function __construct() 
    { 
     if(!$this->isCustomer()) 
     { 
      throw new \Exception('ERROR', 1); 
     } 
    } 
} 
+0

但CustomerPrivate類的對象如何能夠在客戶的同一時間實例?那麼我應該如何定義客戶類? – mlattari

+0

非常感謝!你幫了我很多。 – mlattari

+0

我嘗試過性狀,但它部分解決問題。我可以在對象的特徵中使用特性和方法,但對象不是特性的實例....對於接口,我有相反的情況;-) – mlattari

0

好的。我終於明白了!

Trait CustomerTrait { 

    } 

    interface Customer {  

    } 

    class CustomerCompany extends Company implements Customer { 

     use CustomerTrait; 
    } 

    class CustomerPrivate extends ContractorPrivate implements Customer { 

     use CustomerTrait; 
    }