Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP use statement for namespace

Maybe this is weird question, but I can't work it out what happens internally in php when you write:

use garcha\path\class;

I'm not asking about purpose of namespaces, but about that statement itself, even 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 it remember the names? Does it happen just on compile time? and not run time? something like just describing the function.

like image 553
George Garchagudashvili Avatar asked Oct 31 '22 17:10

George Garchagudashvili


1 Answers

It's not a very complex algorithm (For 5.5, in 5.6 described part for class-names is the same).

  1. If it is necessary, instance of HashTable is created. It keeps import (used namespace classes).
  2. In case of using as keyword, this name is used as an alias. Else used last component of imported class name (for XXX\YYY\ZZZ, name would be ZZZ). Convert it to lower case.
  3. Check for self/parent, it can not be used as name for alias.
  4. Check if this name already exists in class_table (using current namespace, if it has been declared).
  5. Add this alias to special HashTable (mentioned in p.1).

Where is this table used?

Just during compilation for resolving class names.

There is one more interesting thing about aliases - it has scope as namespace block:

<?php

namespace nsC
{
    class classC {}
}

namespace nsA
{
    use nsC\classC as importC;
    new importC();
}

namespace nsB
{
    // ERROR!
    new importC(); // or \nsA\importC()
}
like image 176
Mark.Ablov Avatar answered Nov 15 '22 04:11

Mark.Ablov