【问题标题】:Using object property as default for method property使用对象属性作为方法属性的默认值
【发布时间】:2008-08-04 17:51:13
【问题描述】:

我正在尝试这样做(这会产生意外的 T_VARIABLE 错误):

public function createShipment($startZip, $endZip, $weight = 
$this->getDefaultWeight()){}

我不想在其中输入一个幻数来表示重量,因为我使用的对象有一个"defaultWeight" 参数,如果您不指定重量,所有新货物都会获得该参数。我不能将defaultWeight 放入货件本身,因为它会从货件组更改为货件组。还有比以下更好的方法吗?

public function createShipment($startZip, $endZip, weight = 0){
    if($weight <= 0){
        $weight = $this->getDefaultWeight();
    }
}

【问题讨论】:

    标签: php parameters error-handling


    【解决方案1】:

    这也好不了多少:

    public function createShipment($startZip, $endZip, $weight=null){
        $weight = !$weight ? $this->getDefaultWeight() : $weight;
    }
    
    // or...
    
    public function createShipment($startZip, $endZip, $weight=null){
        if ( !$weight )
            $weight = $this->getDefaultWeight();
    }
    

    【讨论】:

      【解决方案2】:

      布尔 OR 运算符的巧妙技巧:

      public function createShipment($startZip, $endZip, $weight = 0){
          $weight or $weight = $this->getDefaultWeight();
          ...
      }
      

      【讨论】:

        【解决方案3】:

        这将允许您传递 0 的权重并且仍然可以正常工作。请注意 === 运算符,它检查权重是否在值和类型中都匹配“null”(与 == 相反,它只是值,因此 0 == null == false)。

        PHP:

        public function createShipment($startZip, $endZip, $weight=null){
            if ($weight === null)
                $weight = $this->getDefaultWeight();
        }
        

        【讨论】:

        • [@pix0r](#2213) 这是一个很好的观点,但是,如果您查看原始代码,如果权重作为 0 传递,它将使用默认权重。
        【解决方案4】:

        您可以使用静态类成员来保存默认值:

        class Shipment
        {
            public static $DefaultWeight = '0';
            public function createShipment($startZip,$endZip,$weight=Shipment::DefaultWeight) {
                // your function
            }
        }
        

        【讨论】:

          【解决方案5】:

          如果您使用的是 PHP 7,可以改进 Kevin 的回答:

          public function createShipment($startZip, $endZip, $weight=null){
              $weight = $weight ?: $this->getDefaultWeight();
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-09-03
            • 2016-08-15
            • 2012-07-11
            • 2012-03-13
            • 2010-12-05
            • 1970-01-01
            • 2016-03-17
            • 1970-01-01
            相关资源
            最近更新 更多