Calling another constructor from a constructor in PHP
I want a few constructors defined in a PHP class. However, my code for the constructors is currently very similar. I would rather not repeat code if possible. Is there a way to call other constructors from within one constructor in a php class? Is there a way to have multiple constructors in a PHP class?
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;
}
}
I know that I could solve this by creating for instance some Init methods. But is there a way around this?
You can't overload functions like that in PHP. If you do this:
class A {
public function __construct() { }
public function __construct($a, $b) { }
}
your code won't compile with an error that you can't redeclare __construct()
.
The way to do this is with optional arguments.
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;
}
}
And if you really have to have completely different arguments, use the Factory pattern.
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);
精彩评论