Le 02/07/2026 à 16:41, Michael Morris a écrit :
This is tangential to the function autoload discussion.
An idea that popped into my head an hour ago, that I don't have
another PHP Dev to talk to about, what if you could register a
function that is called by PHP the first time it sees a namespace
declared?
This would allow functions and for that matter constants of the
namespace to be declared before they get called. It isn't as clean as
waiting until the function call itself is being called, but maybe
that's for the best. After all, if you have a dozen 10 line utility
functions do you necessarily want 10 files.
Again, I don't know the engine, but this doesn't seem like this would
be that hard to do. Note that how autoloaders register themselves to
this function, resolve what to load and so on is a separate can of worms.
As to what to call it, maybe spl_namespace_register($callback,
$prepend). The callback gets the string of the namespace that PHP just
saw for the first time and it gets to execute before any code in that
namespace gets to execute.
Thoughts?
Interesting idea, not sure whether it's viable or not.
As of how I understand it, there are multiple ways to do this and all of
them will imply different ways developers can use such feature.
With the namespace order, for instance, imagine the very first namespace
declaration is "namespace Foo\Bar\Baz;": what is the order of
declarations that will be sent to callbacks?
* Will the callbacks receive "Foo\Bar\Baz" as argument directly and be
called only once?
* Will they be called once per sub-namespace? If yes, will it be like
calling the callback three times, like this: `$callback('Foo');
$callback('Foo\\Bar'); $callback('Foo\\Bar\\Baz'); `
* How should it propagate if other sub-namespaces of these namespaces
are declared? Like, if you have statements like "namespace Foo\Bar
{} namespace Foo\Baz {}" , would it call registered callbacks like
"Foo -> Foo\Bar -> Foo\Baz", or should it do like no1 and just go
with "Foo\Bar -> Foo\Baz"?
* Or something else?
There might be other issues, but that's my "hot reaction" when reading
your suggestion :)