从PHP中的构造函数调用另一个构造函数

Bri*_*ian 3 php constructor multiple-constructors

我想在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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

cle*_*tus 5

你不能在PHP中重载这样的函数.如果你这样做:

class A {
  public function __construct() { }
  public function __construct($a, $b) { }
}
Run Code Online (Sandbox Code Playgroud)

您的代码将无法使用您无法重新声明的错误进行编译__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;
  }
}
Run Code Online (Sandbox Code Playgroud)