Pergunta

Let's say I have this class.

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

And I instantiate it as:

$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

Foi útil?

Solução

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\n";
     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\n";
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top