我想在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方法来解决这个问题。但是有办法解决这个问题吗?
答案 0 :(得分: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;
}
}
答案 1 :(得分:3)
如果你真的必须有完全不同的参数,请使用工厂模式。
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);