Die gebruik van voorwerp eiendom as verstek vir metode eiendom
-
08-06-2019 - |
Vra
Ek probeer om hierdie (wat 'n onverwagse T_VARIABLE fout produseer) doen:
public function createShipment($startZip, $endZip, $weight =
$this->getDefaultWeight()){}
Ek wil nie 'n magic nommer in daar te vestig om gewig sedert die voorwerp Ek gebruik 'n "defaultWeight"
parameter dat alle nuwe besendings kry as jy nie 'n gewig spesifiseer. Ek kan nie die defaultWeight
in die verskeping self, want dit verander van verskeping groep gestuur groep. Is daar 'n beter manier om dit te doen as die volgende?
public function createShipment($startZip, $endZip, weight = 0){
if($weight <= 0){
$weight = $this->getDefaultWeight();
}
}
Oplossing
Dit is nie veel beter:
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();
}
Ander wenke
netjiese strik met boolean OR operateur:
public function createShipment($startZip, $endZip, $weight = 0){
$weight or $weight = $this->getDefaultWeight();
...
}
Dit sal jou toelaat om 'n gewig slaag van 0 en nog behoorlik werk. Let op die === operateur, hierdie tjeks om te sien of gewig wedstryde "nul" in beide waarde en tipe (in teenstelling met ==, wat net waarde, so 0 == null == vals).
PHP:
public function createShipment($startZip, $endZip, $weight=null){
if ($weight === null)
$weight = $this->getDefaultWeight();
}
Jy kan 'n statiese klas lid te gebruik om die standaard te hou:
class Shipment
{
public static $DefaultWeight = '0';
public function createShipment($startZip,$endZip,$weight=Shipment::DefaultWeight) {
// your function
}
}
Die verbetering op antwoord Kevin se as jy met behulp van PHP 7 jy kan doen:
public function createShipment($startZip, $endZip, $weight=null){
$weight = $weight ?: $this->getDefaultWeight();
}