I must have misunderstood the PHP keyword "use"

I am using an application with PHP namespaces and I thought that instead of doing ...

\MyNamespace\ClassName::MyFunction(); 

I could do

 use MyNamespace; ClassName::MyFunction(); 

if I use this object many times on the page. This does not work for me. I need to use the first method.

What am I missing in the use keyword?

+4
source share
3 answers

use will basically create a link to its argument using the last name (unless otherwise specified). To use ClassName without having to constantly indicate your namespace, you need to import the following:

 use \MyNamespace\ClassName; 

So, ClassName set as a reference to the type located in \MyNamespace\ClassName .

Similar to how Javas import works, not how C # s using , which imports the entire namespace.

+4
source

You need to import / use the exact class name:

 use MyNamespace\ClassName; ClassName::myFunction(); 

You can also use the following syntax:

 use MyNamespace\MySubnamespace; MySubnamespace\MyClassname::doSth(); MySubnamespace\AnotherClassname::doSthElse(); 

which allows you to use multiple classes from the same namespace without the need to import each of them.

0
source

You should try:

 use \MyNamespace\ClassName as MyClassName; MyClassName::MyFunction(); 
0
source

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


All Articles