2017-10-07 40 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 
相关问题