使用对象属性作为方法属性的默认值
时间:2020-03-05 18:37:35 来源:igfitidea点击:
我正在尝试执行此操作(这会产生意外的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(); } }
解决方案
回答
这不是更好:
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(); }
回答
这将使我们传递的权重为0并仍然可以正常工作。注意===运算符,它检查权重在值和类型上是否都匹配" null"(与==相反,后者只是值,所以0 == null == false)。
PHP:
public function createShipment($startZip, $endZip, $weight=null){ if ($weight === null) $weight = $this->getDefaultWeight(); }
回答
我们可以使用静态类成员来保存默认值:
class Shipment { public static $DefaultWeight = '0'; public function createShipment($startZip,$endZip,$weight=Shipment::DefaultWeight) { // your function } }
回答
布尔OR运算符的巧妙窍门:
public function createShipment($startZip, $endZip, $weight = 0){ $weight or $weight = $this->getDefaultWeight(); ... }