2013-10-08 29 views
0

我需要建立一個方法,其中一個對象作爲參數傳遞。此方法使用PHP「instanceof」快捷方式。如何使用默認值,如果未設置參數是一個對象

//Class is setting a coordinate. 
class PointCartesien { 
    //PC props 
    private $x; 
    private $y; 

    //Constructor 
    public function __construct($x, $y) { 
     $this->x = $x; 
     $this->y = $y; 
    } 

    //The method in question... It makes the coordinate rotate using (0,0) as default and $pc if set. 
    //Rotation 
    public function rotate($a, PointCartesien $pc) { 
     //Without $pc, throws error if empty. 
     if(!isset($pc)) { 
      $a_rad = deg2rad($a); 

      //Keep new variables 
      $x = $this->x * cos($a_rad) - $this->y * sin($a_rad); 
      $y = $this->x * sin($a_rad) - $this->y * cos($a_rad); 

      //Switch the instance's variable 
      $this->x = $x; 
      $this->y = $y; 
      return true; 
     } else { 
      //... 
     } 
    } 
} 

使用isset()會引發錯誤。我希望它的工作方式是通過將$ pc參數設置爲(0,0)作爲默認值旋轉($ a,PointCartesien $ pc = SOMETHING)。我會怎麼做?

+2

'$ pc'在方法定義中沒有缺省值,所以它是一個必需的參數,在方法調用中沒有指定它將只是一個致命錯誤。嘗試'旋轉($ a,$ pc = null)',然後稍後做一個明確的'isnull()'測試,並根據需要創建0,0對象。 –

回答

2

您需要$pc參數才能進行函數調用,因此您在遇到isset()檢查之前會收到錯誤。嘗試public function rotate($a, PointCartesien $pc = null) {,然後使用is_null檢查代替isset

相關問題