Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP same namespace for several classes

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.

like image 467
enzo Avatar asked Oct 22 '25 07:10

enzo


2 Answers

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".

like image 89
Will Avatar answered Oct 23 '25 22:10

Will


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

like image 36
vrn53593 Avatar answered Oct 23 '25 20:10

vrn53593



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!