We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Phalconphp 3.0 the use of $this inside a function

Hello everyone,

I just wanted to get some explanation on the issues i had after upgrading to phalcon 3.0,

i have this code working on my micro phalcon 2.0

        $di->set('collections', function(){
            return $this->routeLoader();
        });

After i have upgraded to phalcon 3.0 it suddently does not worked so i have this as my workaround

        $this->collections = $this->routeLoader();
        $di->set('collections', $this->collections);

I just wonder why does my previous code not work on phalcon3 than of 2.

Thanks

It's because Phalcon\Di overrides the default service localization process.. so $this is = DI try using

$_this = $this;
  $di->set('collections', function() use ($_this) {
            return $_this->routeLoader();
});

Read https://blog.phalcon.io/ for more info

Taken from 3.0 release:

Phalcon\Di is now bound to services closures allowing use Phalcon\Di as $this to access services within them. Additionally, closures used as handlers inMvc\Micro are now bound to the $app instance