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.

DI is not recognizing $config as an object?

Hello,

My services.php looks like this:

/** * Setting up the view component */ $di->set('view', function(){ $view = new \Phalcon\Mvc\View(); $view->setViewsDir($config->application->viewsDir); return $view; });

but when I run an application, i keep getting the notice : Trying to get property of non-object in /app/config/services.php on line 44

Line 44 is: $view->setViewsDir($config->application->viewsDir)

So apparently $config is not set-up as an object.

Higher up, I do have /** * Register the global configuration as config */ $di->set('config', $config);

and it is working flawlessly with other DI members, such as the database.

Am I overlooking something or is this standard behaviour?

Thanks! Alex



7.1k
Accepted
answer
edited Nov '14

So I am assuming you're defining the $config object outside of that anonymous function? Like so:

$config = whatever;

/** * Setting up the view component */ 
$di->set('view', function(){ 
    $view = new \Phalcon\Mvc\View(); 
    $view->setViewsDir($config->application->viewsDir); 
    return $view; 
});

If so, then yes, you're simply overlooking something. $config is not in scope within the anonymous function, so you need to do this:

$config = whatever;

/** * Setting up the view component */ 
$di->set('view', function() use ($config){ 
    $view = new \Phalcon\Mvc\View(); 
    $view->setViewsDir($config->application->viewsDir); 
    return $view; 
});

Note my addition of use ($config), which adds that variable into scope for the anonymous function. There is nothing that magically converts $config into a call to the config object stored in your DI, so you need to explicitly pass that into the anonymous function as I demonstrated.



3.2k

Brilliant in its simplicity, thanks a million! Alex

Any time :)