问题
I'm new to Composer and I just can't figure out on how to autoload non-class based files.
I have tried adding the file to the files
array in composer.json and then running composer install
but I had no luck.
My composer.json looks like:
{
"name": "app",
"description": "",
"require": {
"mongodb/mongodb": "^1.2"
},
"autoload":{
"files":["src/lib/config.php"]
}
}
Here is the non-class based file, config.php
$foo = "Hello";
And this is where I would call it:
require_once("vendor/autoload.php");
echo $foo;
The above throws an error of undefined variable: foo
.
Or perhaps the file might be autoloaded and maybe I could be in the wrong namespace. If this is the case, how would I call this file.
回答1:
I disagree with @MarkBaker comment. In fact file will be automatically loaded but it's impossible to declare variables in such files.
For example if you put into this config.php
file the following function:
function hello()
{
echo "hello world";
}
and instead of displaying $foo
you will call this method like so:
hello();
you will get expected result.
The reason why variable is not visible is the way file is loaded via Composer:
function composerRequire4b299eb5732a472abef81c6ea06043af($fileIdentifier, $file)
{
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
require $file;
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
}
}
As you see file is required inside method so all defined variables have scope only in this method so they won't be visible after that (this is how PHP works).
So answering our question this is expected behavior. You shouldn't declare any variables in auto-loaded files by Composer. If you need similar functionality, you should require file manually.
Of course I don't think you should really declare variables in configuration files. You should rather return array of settings and then assign this array to global $config
variable (simplest solution) or use class that will hold those settings and get configuration from this class (something like this is made in Laravel for example).
来源:https://stackoverflow.com/questions/47891255/composer-require-and-use-non-class-file