Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Composer autoloading files return Undefined variable

Hello i have problem with composer when i autoload my config file.

In my composer.json i create

{
"require": {"monolog/monolog": "1.7.*@dev"},
"autoload":{
    "files": ["config/application.config.php"]
    }
}

I want to autoload my config file, and in my test.php file i put :

// Get composer autoloading
require 'vendor/autoload.php';


use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\FirePHPHandler;

$logger = new Logger('my_logger');
$logger->pushHandler(new StreamHandler(__DIR__.'/data/logs/log.log', Logger::DEBUG));
$logger->pushHandler(new FirePHPHandler());

$logger->addInfo('test message');

// test
echo $config['logs_dir'];

My application.config.php file contain

/*
 * Data paths
 */
$config['cache_dir'] = 'data/cache';
$config['logs_dir']  = 'data/logs';

I get notice when i try to print value in my test.php calling echo $config['logs_dir']. File is succesful loaded by composer but notice what i get

Notice: Undefined variable: $config in D:\xampp\htdocs\MCF3\index.php on line 18

like image 567
Ivan Avatar asked Jan 24 '14 16:01

Ivan


1 Answers

When Composer includes the file via require it is doing so within a function, and so doing:

$config['cache_dir'] = 'data/cache';

doesn't create a variable in the global scope. If you want to be able to read/write global variables you should explicitly use the $GLOBALS keyword.

$GLOBALS['config']['cache_dir'] = 'data/cache';
like image 60
Danack Avatar answered Oct 22 '22 22:10

Danack