سؤال

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
*/
هل كانت مفيدة؟

المحلول

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();

نصائح أخرى

In short, no. The only way to invoke these methods would be to call them within each individual method.

class Foo{
   public function bar(){
      $this->before();
      echo 'foo::bar';
      $this->after();
   }

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

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

This would output as expected:

/*
before any methods
foo::bar
after any methods
*/
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top