Hey Theodore, On Mon, May 20, 2019 at 7:17 PM Theodore Brown <theodor...@outlook.com> wrote:
> Every time function autoloading been brought up in the past, there > have been concerns about performance issues when calling a global > function from inside a namespace. E.g. calling `strlen` in a loop > would become far slower if every call has to trigger the autoloader. > > But isn't it extremely rare to override global functions in a > namespace? And even if they are overridden, how common is it to call > an overridden function in the same namespace that exists in a > different file? > > Would it be possible to handle this rare case with a per-file option > like `declare(root_fallback=0);`? > > Consider the following code examples: > > # example_1.php > ```php > namespace Foo; > > echo strlen('test'); > // PHP would first check if Foo\strlen exists. If not, it would check > // whether \strlen exists. Since it does, it would call the built-in > // function as expected without triggering the autoloader. > ``` > > # example_2.php > ```php > namespace Foo; > > function strlen(string $str) {...} > > echo strlen('test'); > // PHP would first check if Foo\strlen exists. Since it is defined in > // the same file, it would be called without falling back to the > // global function or triggering the autoloader. > ``` > > # example_3.php > ```php > namespace Foo; > > use function Bar\strlen; > > echo strlen('test'); > // PHP would first check if Bar\strlen exists. If not, it would > // trigger the autoloader rather than falling back to the global > // function. The same thing would occur for any qualified function > // call. E.g. without "use function" the following could be written: > echo \Bar\strlen('test'); > ``` > > # example_4.php > ```php > namespace Foo; > > echo my_function('test'); > // PHP would first check if Foo\my_function exists. If not, it would > // check whether \my_function exists. If not, the autoloader would be > // triggered. > ``` > > # example_5.php > ```php > declare(root_fallback=0); > > namespace Foo; > > echo strlen('test'); > // PHP would first check if Foo\strlen exists. If not, it would > // trigger the autoloader rather than falling back to the global > // function, since root fallback is disabled in the file. > ``` > > What are your thoughts about this approach? > > Personally I would rarely have to disable root fallback, since I like > to group functions in a single file per namespace. But it seems like > this would be a good way to enable function autoloading that works > with namespaces spread across multiple files and doesn't slow down > performance. > I do like the approach, as it makes the (better) fallback-less function usage opt-in, which is currently only fixed by coding-standards tooling. To be clear, would this lead to a "Fatal error: Uncaught Error: Call to undefined function" in case of autoloader failure? Greets, Marco Pivetta http://twitter.com/Ocramius http://ocramius.github.com/