How to turn a zend helper to a singleton?
I need to use a view helper to make counts in a bunch of different partials. 开发者_Python百科In the partials I can't access view variables, but I can access helpers, so I created this simple class.
class Zend_View_Helper_Counter extends Zend_View_Helper_Abstract{
protected $count = 0;
public function counter(){
return $this;
}
public function add($i = 1){
$this->count = $this->count + (int) $i;
return $this;
}
public function get(){
return $this->count;
}
public function set($count){
$this->count = (int) $count;
return $this;
}
}
However this <?php echo $this->counter()->add()->get()?>
Always returns 1. I guess this is because it's always a different instance of the class. How would I need to change the counter()
function so that it can count through all the views and partials?
Use statics:
static protected $count = 0; public function add($i = 1){ self::$count = self::$count + (int) $i; return $this; }
Write a separate counter singleton and then do:
public function get(){ return Counter::getInstance(); } public function add($i = 1){ Counter::getInstance()->add($i); return $this; }
If you want, you may also extend it by using named counters and then $count would be an array.
精彩评论