2016-05-29 170 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; 
    }