我有以下情况:
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 :(得分: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!
}
或强>
您可以使用特征。 特征非常灵活,但只支持PHP 5.4或更高版本
trait Customer
{
}
class PrivateCustomer extends PrivatePerson
{
use Customer; //trait customer
use OtherTrait;
// Customers that are physical persons, but are CUSTOMERS!
}
编辑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);
}
}
}
答案 1 :(得分:0)
行。我终于明白了!
Trait CustomerTrait {
}
interface Customer {
}
class CustomerCompany extends Company implements Customer {
use CustomerTrait;
}
class CustomerPrivate extends ContractorPrivate implements Customer {
use CustomerTrait;
}