On Wed, 2024-07-24 at 22:02 +0200, Tim Düsterhus wrote:
> 
> > I think a better solution would be to have one namespace for all
> > bundled classes, so that a specific namespace is reserved in
> > advance.
> 
> Needing to prefix everything by \PHP or something like this would 
> provide for a terrible developer experience when using the standard
> library.

We're already there.

If I want to have a Directory class, I need to put it in a namespace.

But then, if I'm using namespaces, I need to put a `\` in front of
every built-in class *and* function or else take a performance hit.

So we're already where we need to do \isset, \array_key_exists, etc to
get the built-in functions without doing a local namespace
lookup first.

I think there are several things to consider here:

1. Could we have a global setting (maybe php.ini) that makes all built-
in functions (not built in classes) directly accessible in any
namespace? That is:

// php.ini
AlwaysUseGlobalFunctions = yes

Then:
// myclass.php
namespace foo;
class Bar{

   function MyMethod($a,$b){
      if(array_key_exists($a,$b)){ // no \ before array_key_exists
         // do something
      }
   }
}

And with that option set, PHP will know that array_key_exists *is*
\array_key_exists, even without the slash, and without checking the foo
namespace for an array_key_exists function first?

My understanding is that some built-in functions have their own opcode,
that doesn't get triggered when those built-in functions are called in
a namespace, unless the built-in is called with a `\`.

Having all *functions* default to global would make namespaces a lot
more user friendly to work with, since we wouldn't have to put
backslashes in front of everything.


2. I think built-in classes are nice, but having classes pre-registered
in the global namespace can cause a lot of frustration.

ie. "GlobIterator::__construct() expects at most 2 arguments, 3 given".

Except, my GlobIterator takes exactly three arguments, so why does....
Oh. I see, there's already a GlobIterator registered.

I think the sane approach is to have the (user land) developers pull
built-in classes into the global namespace when needed with `use`.

If I want the built-in GlobIterator, I should specify that with:
use \spl\GlobIterator;

Then I know there's a GlobIterator class because I just called for it.

Reply via email to