在PHP中从构造函数调用另一个构造函数

3

我想在PHP类中定义几个构造函数。然而,我的构造函数代码目前非常相似。如果可能的话,我宁愿不重复编写代码。在PHP类中有没有一种方法可以从一个构造函数中调用其他构造函数?是否可以在PHP类中拥有多个构造函数?

function __construct($service, $action)
{
    if(empty($service) || empty($action))
    {
        throw new Exception("Both service and action must have a value");
    }
    $this->$mService = $service;
    $this->$mAction = $action;

    $this->$mHasSecurity = false;
}
function __construct($service, $action, $security)
    {
        __construct($service, $action); // This is what I want to be able to do, so I don't have to repeat code

        if(!empty($security))
        {
            $this->$mHasSecurity = true;
            $this->$mSecurity = $security;
        }
    }

我知道我可以通过创建一些初始化方法来解决这个问题。但是有没有其他方法可以解决这个问题?

2个回答

5

在PHP中,您不能像那样重载函数。如果您这样做:

class A {
  public function __construct() { }
  public function __construct($a, $b) { }
}

如果您的代码出现错误,提示您无法重新声明__construct(),则需要使用可选参数。

做法是使用可选参数。

function __construct($service, $action, $security = '') {
  if (empty($service) || empty($action)) {
    throw new Exception("Both service and action must have a value");
  }
  $this->$mService = $service;
  $this->$mAction = $action;
  $this->$mHasSecurity = false;
  if (!empty($security)) {
    $this->$mHasSecurity = true;
    $this->$mSecurity = $security;
  }
}

4

如果你确实需要完全不同的参数,可以使用工厂模式。

class Car {       
   public static function createCarWithDoors($intNumDoors) {
       $objCar = new Car();
       $objCar->intDoors = $intNumDoors;
       return $objCar;
   }

   public static function createCarWithHorsepower($intHorsepower) {
       $objCar = new Car();
       $objCar->intHorses = $intHorsepower;
       return $objCar;
   }
}

$objFirst = Car::createCarWithDoors(3);
$objSecond = Car::createCarWithHorsePower(200);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接