Search code examples
phpoopmagic-methods

Invoke special method before any method of my class in PHP


Is there a special method that when I call any class's method, it will be invoked?

Below there's an example that explains my problem:

class Foo{
   public function bar(){
      echo 'foo::bar';
   }

   public function before(){
      echo 'before any methods';
   }

   public function after(){
      echo 'after any methods';
   }
}

$foo = new Foo;
$foo->bar();

The output should be:

 /*
    Output:
    before any methods
    foo::bar
    after any methods
*/

Solution

  • personally i don´t like this solution, but you are able to use the magic method __call:

    /**
     * @method bar
     */
    class Foo{
    
        public function __call($name, $arguments)
        {
            $myfunc = '_'.$name;
            $this->before();
            if (method_exists($this,$myfunc)) {
                $this->$myfunc();
            }
            $this->after();
        }
    
        public function _bar(){
            echo 'foo::bar';
        }
    
        public function before(){
            echo 'before any methods';
        }
    
        public function after(){
            echo 'after any methods';
        }
    }
    
    $foo = new Foo;
    $foo->bar();