El uso de la propiedad del objeto como valor predeterminado para el método de la propiedad

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

  •  08-06-2019
  •  | 
  •  

Pregunta

Estoy tratando de hacer esto (lo que produce un inesperado T_VARIABLE de error):

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

No quiero poner un número mágico en no para de peso ya que el objeto que estoy usando tiene un "defaultWeight" parámetro que todos los nuevos envíos de conseguir si no se especifica un peso.No puedo poner la defaultWeight en el envío, porque los cambios de envío de grupo para el envío de grupo.Hay una manera mejor de hacerlo que el siguiente?

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

Solución

No es mucho mejor:

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

Otros consejos

Truco con booleanos O de operador:

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

Esto le permitirá pasar de un peso de 0 y todavía funcionan correctamente.Aviso de la === operador, este comprueba si el peso de los partidos "null" en tanto valor y tipo (como opuesto a ==, que es justo valor, por lo tanto, 0 == null == false).

PHP:

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

Usted puede utilizar un miembro estático de la clase para mantener el valor predeterminado:

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

Mejora de Kevin respuesta si usted está usando PHP 7 usted puede hacer:

public function createShipment($startZip, $endZip, $weight=null){
    $weight = $weight ?: $this->getDefaultWeight();
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top