Pergunta

Estou tentando fazer isso (que produz um erro T_VARIABLE inesperado):

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

Não quero colocar um número mágico para peso, pois o objeto que estou usando tem um "defaultWeight" parâmetro que todas as novas remessas recebem se você não especificar um peso.não consigo colocar defaultWeight no próprio transporte, pois muda de grupo de transporte para grupo de transporte.Existe uma maneira melhor de fazer isso do que a seguinte?

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

Solução

Isso não é muito melhor:

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

Outras dicas

Truque legal com operador booleano OR:

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

Isso permitirá que você passe um peso de 0 e ainda funcione corretamente.Observe o operador ===, que verifica se o peso corresponde a "nulo" tanto no valor quanto no tipo (em oposição a ==, que é apenas valor, então 0 == nulo == falso).

PHP:

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

Você pode usar um membro de classe estático para manter o padrão:

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

Melhorando a resposta de Kevin, se você estiver usando PHP 7, você pode fazer:

public function createShipment($startZip, $endZip, $weight=null){
    $weight = $weight ?: $this->getDefaultWeight();
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top