4

I am new to the composer and here is my composer.json file:

{
    "name": "asd",
    "authors": [
        {
            "name": "test",
            "email": "test@me.com"
        }
    ],
    "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?

Syed Aqeel
  • 1,009
  • 2
  • 13
  • 36
  • Why do you want to use globals after all? That will only cause trouble – Nico Haase Mar 22 '18 at 09:21
  • Yeah you are right that I shouldn't use the variable as global, but the problem is I am converting our app into PSR-4 standard using composer, and there are many function and objects in bootstrapper that I have to call from everywhere in the app, so that what I want. – Syed Aqeel Mar 22 '18 at 10:13
  • putting them in a function is still global anyway so whats the difference so long as your only loading that composer install and associated global vars for the function you need them in and not site wide... – Hayden Thring Jul 01 '23 at 21:27

1 Answers1

2

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();