Ben
Ben

Reputation: 62366

I must be misunderstanding PHP's "use" keyword

I'm using an application with PHP's namespaces and I thought that instead of me doing...

\MyNamespace\ClassName::MyFunction();

I could do

use MyNamespace;
ClassName::MyFunction();

if I'm using that object many times within the page. This isn't working for me. I keep having to use the first method.

What am I missing about the use keyword?

Upvotes: 4

Views: 166

Answers (3)

user1386320
user1386320

Reputation:

You should try like:

use \MyNamespace\ClassName as MyClassName;

MyClassName::MyFunction();

Upvotes: 0

Crozin
Crozin

Reputation: 44376

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 several classes from one namespace without need to import every single one of them.

Upvotes: 0

poke
poke

Reputation: 387557

use will basically create a link to its argument, using the last name (unless otherwise speicified). To use ClassName without having to specify its namespace all the time, you have to import the following:

use \MyNamespace\ClassName;

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

It’s similar to how Java’s import works, and not like C#’s using which imports the whole namespace.

Upvotes: 4

Related Questions