dqq9695
dqq9695
2013-12-15 21:33
浏览 110
已采纳

如何知道方法被调用了多少次?

Let's say I have this class.

class foo{
  function a(){
     return $this; 
  }
}

.

$O = new foo(); 
$O->a()
  ->a()
  ->a();

Is there any way to know, in that last function ->a() how many times it was called before? So, I could output like 'method ->a() has been called twice before this.' I would like to find out this, without using increment values like declaring a property and then increment it increment it, everytime it is called in a function.

I am just hopping if there is a hidden feature in OOP that can provide for this solution

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongxian2863
    dongxian2863 2013-12-15 21:35
    已采纳

    You can use a static variable inside the method:

    class foo{
    
      function a(){
         // $count will be initialized the first time a() was called
         static $count = 0;
         // counter will be incremented each time the method gets called
         $count ++;
    
         echo __METHOD__ . " was called $count times
    ";
         return $this;
      }
    }
    

    Note that static has a different meaning when used inside a method or function and it has nothing to do with static class members - although it is the same keyword. It means that the variable will be created and initialized only once when the method has been called for the first time.

    However, in the example above there is no way to reinitialize that counter. If you want to do that you may introduce a parameter or something like this. Also you may not use a static variable but an object property.. There are tousand ways to do it, tell me your exact application needs I may give a more specific example....


    In comments it was suggested to use a decorator for this job. I like this idea and will give a simple example:

    class FooDecorator
    {
    
        protected $foo;
        protected $numberOfCalls;
    
        public function __construct($foo) {
            $this->foo = $foo;
            $this->reset();
        }
    
        public function a() {
            $this->numberOfCalls++;
            $this->foo->a();
            return $this;
        }
    
        public function resetCounter() {
            $this->numberOfCalls = 0;
        }
    
        public function getNumberOfCalls() {
            return $this->numberOfCalls;
        }
    }
    

    Usage example:

    $foo = new FooDecorator(new foo());
    $foo->a()
        ->a()
        ->a();
    
    echo "a() was called " . $foo->getNumberOfCalls() . " times
    ";
    
    点赞 评论

相关推荐