search

Home  >  Q&A  >  body text

When PHP uses a namespace, why should it be precise to a class under the namespace?

The code under the Tool.class.php file is:

namespace CompanyTool;

class Tool{

}

My question is why if you use the Tool class in other files, you must write like this: use Company\Tool\Tool

I thought it would be enough to write use Company\Tool (what I understand means that you can use any class in this space).
I hope you can tell me, thank you.

曾经蜡笔没有小新曾经蜡笔没有小新2798 days ago690

reply all(3)I'll reply

  • 巴扎黑

    巴扎黑2017-06-06 09:55:57

    C++ has what you wantusing namespace xxx.

    Why PHP doesn’t directly introduce the entire namespace? Only those involved in the design probably know this.

    I guess the reason is to avoid introducing too many unnecessary things at once. Batch introduction is not recommended in various languages.

    reply
    0
  • ringa_lee

    ringa_lee2017-06-06 09:55:57

    1. Accurate to class can improve performance. If it is only accurate to a certain directory, every time a class is loaded, the compiler still needs to go to the directory to find whether the class exists.

    2. Accurate to the class to avoid conflicts. If the same class name exists in two directories, if it is accurate to the class, conflicts can be avoided very well.

    3. Easy to optimize, C# has the features mentioned by the poster, but C# is directly compiled into an executable file, but Java adopts a class-accurate approach, both are interpreted languages, and the benefit of this is beneficial to the later stage. Interpretation optimization allows classes to be found accurately and reduces cache consumption.

    reply
    0
  • PHPz

    PHPz2017-06-06 09:55:57

    You can use a class or a namespace

    namespace A;
    class B
    {
        public function test() {}
    }

    Quote

    namespace C;
    use A;
    $b = new A\B();
    $b->test();

    or

    namespace C;
    use A\B;
    $b = new B();
    $b->test();

    If you write it like that, autoload will definitely not be able to find this file. If the file is loaded manually, it must be written that way based on the understanding of the namespace. And I think the layout of the question should be namespace CompanyTool; right

    reply
    0
  • Cancelreply