문제

내가 하려는 이(을 생산하는 예상치 못한 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();
}

다른 팁

깔끔한 트 boolean 사를 진행하고 있습니다.

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
    }
}

을 개선에 따라 케빈의 응답을 사용하는 경우 PHP7 할 수 있습니다:

public function createShipment($startZip, $endZip, $weight=null){
    $weight = $weight ?: $this->getDefaultWeight();
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top