使用对象属性为默认方法财产
问题描述:
我试图做到这一点(这会产生意想不到的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重量并仍能正常工作。注意===运算符,它检查是否在weight和type中匹配“null”(相对于==,它只是value,所以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();
...
}
[@ pix0r]( #2213)这是一个很好的观点,但是,如果您查看原始代码,如果权重传递为0,则它使用默认权重。 – Kevin 2008-08-06 22:58:35