2013-05-09 123 views
2

我需要一種方法,它會在每個公共方法之前運行。如何在PHP中的所有公共方法之前調用方法?

有沒有像公共方法__call的方法?

我想在我的setter方法之前修剪所有參數。

+0

還有其他的一些方法嗎? – Hydroid 2013-05-09 18:21:24

+0

我想修改setter方法中的所有參數 – 2013-05-09 18:22:12

+4

與其他一些語言一樣,PHP沒有過濾前後的功能。一些PHP框架提供了這個功能,但是在他們不在的時候,你將不得不使用包裝器方法來實現你的目標。 – 2013-05-09 18:26:46

回答

0

不,沒有像公共方法__call這樣的機制。但__call()已經是你要找的。如果你嘗試的例子

class A { 

    protected $value; 

    /** 
    * Enables caller to call a defined set of protected setters. 
    * In this case just "setValue". 
    */ 
    public function __call($name, $args) { 
     // Simplified code, for brevity 
     if($name === "setValue") { 
      $propertyName = str_replace("set", "", $name); 
     } 

     // The desired method that should be called before the setter 
     $value = $this->doSomethingWith($propertyName, $args[0]); 

     // Call *real* setter, which is protected 
     $this->{"set$propertyName"}($value); 
    } 

    /** 
    * *Real*, protected setter 
    */ 
    protected function setValue($val) { 
     // What about validate($val); ? ;) 
     $this->value = $val; 
    } 

    /** 
    * The method that should be called 
    */ 
    protected function doSomethingWith($name, $value) { 
     echo "Attempting to set " . lcfirst($name) . " to $value"; 
     return trim($value); 
    } 
} 

$a = new A(); 
$a->setValue("foo"); 

...你會得到以下輸出:

我將定義使用__call 「僞公開」 界面

Attempting to set value to foo 
相關問題