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;
        }
    }

我知道我可以通过创建一些 Init 方法来解决这个问题。但是有没有办法解决这个问题?

4

2 回答 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;
  }
}
于 2009-11-11T00:15:03.293 回答
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);
于 2009-11-11T02:25:05.690 回答