【问题标题】:Calling another constructor from a constructor in PHP从 PHP 中的构造函数调用另一个构造函数
【发布时间】:2010-12-15 07:00:29
【问题描述】:

我想要在 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 方法来解决这个问题。但是有没有办法解决这个问题?

【问题讨论】:

    标签: php constructor multiple-constructors


    【解决方案1】:

    您不能在 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;
      }
    }
    

    【讨论】:

      【解决方案2】:

      如果你真的必须有完全不同的参数,请使用工厂模式。

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

      【讨论】:

        猜你喜欢
        • 2011-03-24
        • 1970-01-01
        • 1970-01-01
        • 2014-03-12
        • 2012-06-22
        • 1970-01-01
        • 1970-01-01
        • 2016-07-03
        • 2015-07-02
        相关资源
        最近更新 更多