php - विधि गुण के लिए ऑब्जेक्ट प्रॉपर्टी को डिफ़ॉल्ट के रूप में उपयोग करना

original title: "php - Using object property as default for method property"


Translate

I'm trying to do this (which produces an unexpected T_VARIABLE error):

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

I don't want to put a magic number in there for weight since the object I am using has a "defaultWeight" parameter that all new shipments get if you don't specify a weight. I can't put the defaultWeight in the shipment itself, because it changes from shipment group to shipment group. Is there a better way to do it than the following?

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


मैं यह करने की कोशिश कर रहा हूं (जो एक अप्रत्याशित T_VARIABLE त्रुटि पैदा करता है): सार्वजनिक फ़ंक्शन createShipment ($ startZip, $ endZip, $ weight = $ this-> getDefaultWeight ()) {} मैं एक जादुई संख्या नहीं डालना चाहता। ..

यह अनुवाद के बाद का सारांश है, अगर आपको पूरा अनुवाद देखने की आवश्यकता है, तो कृपया 'अनुवाद' आइकन पर क्लिक करें


सभी उत्तर
  • Translate

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

  • Translate

    Neat trick with boolean OR operator:

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

  • Translate

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

  • Translate

    You can use a static class member to hold the default:

    class Shipment
    {
        public static $DefaultWeight = '0';
        public function createShipment($startZip,$endZip,$weight=Shipment::DefaultWeight) {
            // your function
        }
    }
    

  • Translate

    Improving upon Kevin's answer if you are using PHP 7 you may do:

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