在PHP中自动调用类中其他几个方法中的一个方法

在PHP中自动调用类中其他几个方法中的一个方法,php,class,oop,methods,Php,Class,Oop,Methods,让我们假设这个类: <?php namespace app; class SimpleClass { protected $url = ''; protected $method = 'GET'; public function __construct( $url, $method = 'GET' ) { $this->url = $url; $this->method = $method; }

让我们假设这个类:

<?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...
    }
使用神奇的方法

  • \uuu call()
    -只要调用不可访问的方法,就会调用
    \uu call
    ,因此这不适用于公共方法,您至少必须重命名为protected
参考:

请注意:这不适用于
public
方法,以下是结果

测试结果:

akshay@db-3325:/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();

?>
akshay@db-3325:/tmp$ php test.php 
Preparing
Preparing
get
Preparing
patch
post
akshay@db-3325:/tmp$ php test.php 
Preparing
Preparing
get
Preparing
patch
post