I am new to the composer and here is my composer.json file:
{
"name": "asd",
"authors": [
{
"name": "test",
"email": "[email protected]"
}
],
"require": {
"vlucas/phpdotenv": "^2.4"
},
"autoload": {
"files": [
"config/bootstrap.php",
"lib/app.php"
],
"classmap": [
"lib/ez_sql/shared/ez_sql_core.php",
"lib/ez_sql/mysql/ez_sql_mysql.php",
"lib/smarty/libs/"
],
"psr-4": {
"App\\" : "app/",
"Sys\\": "system/"
}
}
}
As you can see there is an autoload file config/bootstrap.php in which I have few classes instances, and I want to access these in other files. But the problem is I can't access until I don't declare as GLOBAL variable. For Example:
config/bootstrap.php
$obj1 = new obj();
$GLOBALS['obj2'] = new obj2();
I can access $obj2 in other files like in index.php but can't use $obj1.
Is there any other possible way to use composer autoload file variable in other files instead of declaring as global?
Composer does its autoloading within a function (see the require statement in vendor/composer/autoload_real.php:composerRequireXXX()). The expected use of this is for files containing just functions and classes, not variables. Because functions and classes are always attached to the global scope, those symbols exist after the getLoader function exits. Variables, however, aren't global scope by default and thus are lost when getLoader returns.
You're right in thinking that you must define those variables as global in order for them to survive Composer's scoped autoloading.
You could change config/bootstrap.php in either of these ways to make $obj1 globally-accessible via Composer's autoload files feature:
$obj1 = new obj();
+$GLOBALS['obj1'] = $obj1;
$GLOBALS['obj2'] = new obj2();
or using the global keyword:
+global $obj1;
$obj1 = new obj();
$GLOBALS['obj2'] = new obj2();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With