2017-10-07 44 views
1

讓我們假設這個類:自動調用其他幾個方法,一個方法在PHP類

<?php 

namespace app; 

class SimpleClass { 

    protected $url = ''; 
    protected $method = 'GET'; 

    public function __construct($url, $method = 'GET') 
    { 
     $this->url = $url; 
     $this->method = $method; 
    } 

    public function get() 
    { 
     $this->prepare_something(); 
     // other things... 
    } 

    public function post() 
    { 
     $this->prepare_something(); 
     // other things... 
    } 

    public function patch() 
    { 
     $this->prepare_something(); 
     // other things... 
    } 

    public function put() 
    { 
     // other things... 
    } 

    public function delete() 
    { 
     // other things... 
    } 

    protected function prepare_something() 
    { 
     // preparing... 
    } 

正如你可以在這個類三種方法看; get, post, patch我們利用方法preparing_something,但在方法put, delete我們沒有。我不得不重複3次$this->prepare_something();。有一次在這3種方法get, post, patch。在這3種方法開始時,它是3 lines的調用。

但想象一下,我們有100個方法。我們使用,在30我們不使用。

有沒有辦法在這70種方法中使用auto-call這些方法?沒有寫在這70種方法的每一種中$this->prepare_something();

這只是疼痛,它不覺得權利必須調用所有的時間同樣的方法$this->prepare_something();在某些方法...

回答

2

用魔術方法__call()

  • __call() - 任何時候不可訪問的方法被調用__call將被調用,所以這不適用於公共方法,您將不得不重新命名爲受保護的。

編號:http://php.net/manual/en/language.oop5.magic.php

public function __call($method,$args) 
{ 
     // if method exists 
     if(method_exists($this, $method)) 
     { 
      // if in list of methods where you wanna call 
      if(in_array($method, array('get','post','patch'))) 
      { 
       // call 
       $this->prepare_something(); 
      } 

      return call_user_func_array(array($this,$method),$args); 
     } 
} 

請注意:這不會public方法工作,這裏是的結果。

測試結果:

[email protected]:/tmp$ cat test.php 
<?php 

class Test { 

     public function __call($method,$args) 
     { 
     // if method exists 
     if(method_exists($this, $method)) 
     { 
      // if in list of methods where you wanna call 
      if(in_array($method, array('get','post','patch'))) 
      { 
       // call 
       $this->prepare_something(); 
      } 

      return call_user_func_array(array($this,$method),$args); 
      } 
     } 

    protected function prepare_something(){ 
     echo 'Preparing'.PHP_EOL; 
    } 

    // private works 
    private function get(){ 
     echo 'get'.PHP_EOL; 
    } 

    // protected works 
    protected function patch(){ 
     echo 'patch'.PHP_EOL; 
    } 

    // public doesn't work 
    public function post(){ 
     echo 'post'.PHP_EOL; 
    } 
} 

    $instance = new test; 

    // protected works 
    $instance->prepare_something(); 

    // private works 
    $instance->get(); 

    // protected works 
    $instance->patch(); 

    // public does not work 
    $instance->post(); 

?> 

執行:

[email protected]:/tmp$ php test.php 
Preparing 
Preparing 
get 
Preparing 
patch 
post 
相關問題