views:

163

answers:

2

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?

+3  A: 

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;
  }
}
cletus
A: 

And if you really have to have completely different arguments, use the Factory pattern.

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

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