2009-02-10 51 views
2

我有這個PHP類我怎麼可以給大量的類方法「幾乎」相同的代碼

class myclass{ 
     function name($val){ 
      echo "this is name method and the value is".$val; 
     } 

     function password($val){ 
      echo "this is password method and the value is".$val; 
     } 
    } 

,這裏是如何使用它:

$myclass= new myclass(); 
    $myclass->name("aaa")//output: this is name method and the value is aaa 

它工作得很好,因爲我只有2個方法「名稱」和「密碼」 如果我有大量的方法,將這些方法添加到我的類併爲每個方法編寫相同的代碼並不容易,我想更改我的類讓每個方法都能提供與方法名稱相同的輸出結果?我不想寫所有方法的所有細節,因爲它們幾乎相似,這在PHP中可能嗎? 我希望我很清楚:)

回答

14

您可以覆蓋該類的__call()方法,這是一種「神奇方法」,將在調用不存在的方法時使用。

3

使用__call魔術方法,如下所示:

class myclass 
{ 
    function __call($func, $args) 
    { 
     echo 'this is ', $func, 'method and the value is', join(', ', $args); 
    } 
} 

此功能將被調用的,它沒有一個明確的函數定義的任何功能。

請注意,$ args是一個數組,其中包含函數的所有參數。

相關問題