باستخدام خاصية كائن افتراضي على الطريقة الملكية

StackOverflow https://stackoverflow.com/questions/1453

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

نصائح أخرى

خدعة مع منطقية أو المشغل:

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 يمكنك القيام به:

public function createShipment($startZip, $endZip, $weight=null){
    $weight = $weight ?: $this->getDefaultWeight();
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top