Php namespace operator

This may be a weird question, but I can't figure out what is going on inside php when you write:

use garcha\path\class; 

I am not asking about the purpose of namespaces, but about this very statement, even if it does not allocate any memory, I mean when you even give an alias for some class:

 use garcha\path\class as withNewName; 

Where is it stored? Or how does he remember the names? Does this only happen at compile time? and do not run time? something like just a function description.

+5
source share
1 answer

This is not a very complicated algorithm (for 5.5, in 5.6 the described part for class names is the same).

  • If necessary, an instance of HashTable is created. It saves imports (used namespace classes).
  • When using the as keyword, this name is used as an alias. Else uses the last component of the name of the imported class (for XXX \ YYY \ ZZZ, the name will be ZZZ). Convert it to lowercase.
  • Check self / parent , it cannot be used as a name for an alias.
  • Check if this name exists in class_table (using the current namespace, if one was declared).
  • Add this alias to a special HashTable (see section 1).

Where is this table used?

Only at compile time to resolve class names.

There is another interesting thing about aliases: it has a namespace scope:

 <?php namespace nsC { class classC {} } namespace nsA { use nsC\classC as importC; new importC(); } namespace nsB { // ERROR! new importC(); // or \nsA\importC() } 
+2
source

Source: https://habr.com/ru/post/1201848/


All Articles