We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Undefined variable in View using setVar() function when set DI services

I'm using dispatcher to dispatch custom controller, action, and view:

$Controller = 'contact';
$Action = 'index';
$ViewController = $this->getDI()->get('dispatcher')->getControllerName();
$ViewAction = $this->getDI()->get('dispatcher')->getActionName();
$this->getDI()->get('view')->render($ViewController, $ViewAction, $e);

It is working fine and the controller is being dispatched and view is rendering correctly, but there is one problem in view variables when I set them in the controller:

$this->view->setVar('A', 1);
// or
$this->view->A = 1;

Then in view contact/index.phtml when I try to print $A variable:

echo $A;

I got the following error: Notice: Undefined variable: A in ..XXXXX/app/views/contact/index.phtml on line 1

Any suggestions on how can I assign variables to be used in views. Thank you

edited Aug '14

Maybe (I didn't use dispatcher) would be:

$this->getDI()->get('view')->setVar('A', 1);
edited Aug '14

Hi David, It didn't work! that worked when I was using default app. thank you

edited Aug '14

Make sure you're registering the 'dispatcher' and 'view' services as 'shared':

$di->set('dispatcher', function (){
}, true);
$di->set('view', function (){
}, true);
edited Aug '14

Yes it worked! thank you Phalcon. Can you tell me what is the effect of shared service exactly, and why doesn't it work before even I was setting view service using DI which could be enough ?


When a service is not shared every time you access it, the DI returns a new instance:

#non shared
$this->getDI()->get('dispatcher'); // new Dispatcher() 
$this->getDI()->get('dispatcher'); // new Dispatcher();

$this->getDI()->get('dispatcher'); // new Dispatcher() 
$this->getDI()->get('dispatcher'); // same instance created before