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

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

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 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
    ";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3