Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

A global incrementor service in Phalcon

I try to create a service in Phalcon, that only increments a number.

My Class:

class FormCounter {

    private $counter = 0;

    public function increment() {
        return $this->counter;


In services:

$di->set('formCounter', function () {
    return FormCounter();

In my Form Class I want to create an ID in every form with increments. The first form i create will have ID "form_1", second "form_2" etc.

$this->form_id = $this->getDi()->getFormCounter()->increment();

But it won't increment. It returns 1 everytime. How do I do this without using global variables?


Try with return $this->counte++;

Now it only returns 0 every time.

$di->set('formCounter', function () {
    return FormCounter();

New object FormCounter created when you call it in this set. Try to set service as shared

$di->setShared('formCounter', function () {
    return FormCounter();

Perfect! Thanks!