使用对象属性作为方法属性的默认值
-
08-06-2019 - |
题
我正在尝试执行此操作(这会产生意外的 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();
}
其他提示
布尔 OR 运算符的巧妙技巧:
public function createShipment($startZip, $endZip, $weight = 0){
$weight or $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
}
}
如果您使用 PHP 7,则可以改进 Kevin 的答案:
public function createShipment($startZip, $endZip, $weight=null){
$weight = $weight ?: $this->getDefaultWeight();
}
不隶属于 StackOverflow