Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the 'use' keyword trigger autoloading in PHP?

Tags:

php

autoload

In the example below, at what point does the autoloader load the class file, if at all? For example, if $boolean_test === false does the Subpackage get loaded?

use Org\Group\Package\Subpackage; // autoloader triggered here?
if ($boolean_test) {
    Subpackage::method(); // or here?
}

I prefer the use statement near the top of the code so I can see what packages are used in the page and for slightly better readability. But, if packages are only used based on conditionals, I may be loading unneeded resources.

like image 642
S.Walker Avatar asked Feb 08 '23 14:02

S.Walker


1 Answers

No use does not trigger autoloading. You can have an invalid use at the top of your file and PHP won't complain.

Autoloading happens when you attempt to use the class.

It's quite easy to test this: https://3v4l.org/OccF3

like image 103
Here2Help Avatar answered Feb 10 '23 11:02

Here2Help