João Serra
João Serra

Reputation: 519

Autoloading package that contains Class of same name as imported class

I have a project that includes a PHP file that defines a class named Response and I'm auto-loading Guzzle via composer (which also defines it's own Response class)

The question is do I run the risk that PHP might get confused as to which Response class it should use? If I use Response by itself I don't run the risk that it will somehow fetch the Guzzle class unless I do a use statement right?

I think it's fine unless I do the use statement but I just wanna be sure.

Upvotes: 0

Views: 783

Answers (2)

MikO
MikO

Reputation: 18741

You don't have any risk of conflicts, that's why PHP Namespaces exist!
Although the short name of both classes are the same, their FQCN (Fully Qualified Class Name) are different, so there's no chance of getting confused.

Guzzle's Response class is:

\Guzzle\Http\Message\Response

Your class would be something like:

\MyApp\Response 

(or just \Response if you didn't set a namespace for it, which is a very bad practise!)

You can use either of them in your classes, or even both, as long as you set an alias for one of them:

use \MyApp\Response;
use \Guzzle\Http\Message\Response as GuzzleResponse;

// ...

$myResponse = new Response();
$guzzleResponse = new GuzzleResponse();

Upvotes: 1

Spears
Spears

Reputation: 2208

As long as the classes got individual namespaces.

Composer (and its autolaoder) will resolve the namespace with the classname. So if you use your own class ("Class1") and the foreign class ("Class2") with the same classname ("Classname") with different namespaces e.g.

namespace \Me\MyPackage\Classname

namespace \Guzzle\Classname

you will be fine. If you wanna create an instance of one of the classes just type the full qualified namespace e.g.

$var1 = new \Me\MyPackage\Classname();

Upvotes: 0

Related Questions