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