Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

cesarmd's avatar

How to keep track of available variables in a PHP file when you have several 'require's?

Coming from a Javascript (Node) background, I find it hard to understand what to expect when you import a file in PHP with require. In Javascript most of the time you use named imports like import Task from './task' instead of importing the whole file and accessing variables inside it. While learning PHP I quickly realized that it's going to be really hard to remember what each file has access to. I wrote a comment about it here.

The question: is there some kind of convention that I should keep in mind while writing PHP in order to avoid these conflicts? How are we expected to know, for example, that when you do require 'core/bootstrap.php'; you'll have access to a Router variable? Or to know that the controller/index.php has access to the $database object even though it's not being imported explicitly?

0 likes
4 replies
aurawindsurfing's avatar

Hey @cesarmd

Being new to PHP myself I found this question quite interesting and here is what I found:

The require() function is identical to include(), except that it handles errors differently. If an error occurs, the include() function generates a warning, but the script will continue execution. The require() generates a fatal error, and the script will stop.

Have a look here: https://stackoverflow.com/questions/2418473/difference-between-require-include-require-once-and-include-once

Tray2's avatar

This can be a bit confusing in the start yes.

I would not use require but rather an autoloader to handle that for me just like you are writing.

In the top of your class just under the namespace you add all the classes you want your class to have access to.

For example in this test class.


namespace Tests\Feature\Http;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Author;
use App\Book;
use App\Format;
use App\Genre;
use App\Score;

So now I can access the Author class anywhere in my class.

    factory(Author::class)->create();

Then you have inheretence where you have access to the parent class methods.

I suggest doing the OOP Bootcamp series here on Laracasts to get you up to speed.

cesarmd's avatar

The answer to my question was just a few videos down the tutorial. Like Tray2 mentioned, people use autoload to load the Classes, and also custom Dependency Injections to handle that problem.

What a relief!

Please or to participate in this conversation.