4

I wanted a clarification on the use of namespaces.

If I have two classes in the same namespace, like this:

<?php

namespace Test\Collection; 

class First{}

And:

<?php

namespace Test\Collection; 

class Second{}

In this case I can use them in this way?

use Test\Collection;

$first = new First();
$second = new Second();

Thanks.

2
  • 2
    And the question is? Why don't you simply test it yourself and see Commented Dec 30, 2015 at 11:18
  • 1
    I tried it, and it does not work as it should specify the class name in the namespace to use, so I wanted to know if there was another way to do this, that I will not include any namespace, but I want to include a single namespace and use all classes. I'm sorry for my english. Thank you Commented Dec 30, 2015 at 11:20

3 Answers 3

8

Not quite.

With your example, you'd need:

<?php

use Test\Collection\First;
use Test\Collection\Second;

$first = new First();
$second = new Second();

Or:

<?php

use Test\Collection;

$first = new Collection\First();
$second = new Collection\Second();

See the documentation for more information. This is known as "namespace importing or aliasing".

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, it was what I wanted to know.
5

you can use multiple classes of a namespace like below

use Test\Collection as Container;

$first = new Container\First();
$second = new Container\Second();

I think second solution from @Will may not work at some cases.

for your better understanding take a look at this explanation. Hope this helps

Comments

4

Anyone interested in doing this from PHP 7 onwards, there is another option:

"From PHP 7.0 onwards, classes, functions and constants being imported from the same namespace can be grouped together in a single use statement"

use some\namespace\{ClassA, ClassB, ClassC as C};
use function some\namespace\{fn_a, fn_b, fn_c};
use const some\namespace\{ConstA, ConstB, ConstC};

Source: Official PHP documentation

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.