Using object property as default for method property Using object property as default for method property php php

Using object property as default for method property


This isn't much better:

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();}


Neat trick with Boolean OR operator:

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


This will allow you to pass a weight of 0 and still work properly. Notice the === operator, this checks to see if weight matches "null" in both value and type (as opposed to ==, which is just value, so 0 == null == false).

PHP:

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