2011-08-19 193 views
1

對不起,對面向對象還是一個新東西。在構造函數中設置默認函數參數

我正在使用CodeIgniter,但這個問題基本上只是PHP OO。

我有爲數衆多的做類似的事情函數的類文件:

function blah_method($the_id=null) 
{     
     // if no the_id set, set it to user's default 
     if(!isset($the_id)){ 
      $the_id = $this->member['the_id'];   
     } 

現在,而不是這樣做,在每次方法在這個類中,我可以在構造函數中設置呢?所以我仍然可以明確地傳遞$ the_id,以覆蓋它,否則它總是默認爲$this->member['the_id'];

這樣做的最優雅方式是什麼?

回答

0

如何將所有初始化數據作爲數組傳遞給構造函數?

public function __construct(array $settings) { 

    // if 'the_id' has not been passed default to class property. 
    $the_id = isset($settings['the_id']) ? $settings['the_id'] : $this->member['the_id']; 
    // etc 
} 
0

我覺得最優雅的方式將是擴展的ArrayObject的類和覆蓋偏移方法,如果您嘗試訪問未設置屬性時調用。然後,您可以返回或設置您需要的內容並忘記構造。

-1

,你可以這樣做:

class A { 

    private $id = null; 
    public function __construct($this_id=null){ 
     $this->id = $this_id; 
    } 

    public function _method1(){ 
     echo 'Method 1 says: ' . $this->id . '<br/>'; 
     return "M1"; 
    } 

    public function _method2($param){ 
     echo 'Method 2 got param '.$param.', and says: ' . $this->id . '<br/>'; 
     return "M2"; 
    } 
    public function __call($name, $args){ 
     if (count($args) > 0) { 
      $this->id = $args[0]; 
      array_shift($args); 
     } 
     return (count($args) > 0) 
      ? call_user_func_array(array($this, '_'.$name), $args) 
      : call_user_func(array($this, '_'.$name)); 
    } 
} 

$a = new A(1); 
echo $a->method1() . '<br>'; 
echo $a->method2(2,5) . '<br>'; 
當然

它的醜陋,並會給您造成一定的混亂,如果你有功能的更多可選變量...

順便說一句,輸出爲:

Method 1 says: 1 
M1 
Method 2 got param 5, and says: 2 
M2 
相關問題