Majiy
Majiy

Reputation: 1920

PHP: What options are there to refactor double used classname?

On a web project there are two classes that have the same name. This was never an issue until now, because the two classes where never used at the same time / in the same script.

Now we require to use both classes in one script, and therefor got ourselves an "Cannot redeclare class" fatal error.

My question is: What options are there to resolve this issue?

The one possible solution would be to rename one of the classes in question, but it is something I would very much like to avoid - one of the classes is part of a third-party software that should not be modified at this level, to remain updateable.

I know there are namespaces - are they a valid option to this problem? I have never used namespaces until now.

Assuming we would put one of the classes into a namespace: Would this resolve the issue? Also, what measures would we need to take to access the now-namespaced class?

Upvotes: 2

Views: 75

Answers (2)

Ulrich Horus
Ulrich Horus

Reputation: 350

How Namespace work: consider we have 2 classes named User in file structure

/Package1/User.php

with content

<?php
    namespace Package1;
    class user {...}

and

/Package2/User.php

with content

<?php
    namespace Package2;
    class user {...}

and now for some reason we decide to use both in some class UserManager in: /Package3/UserManager.php with content:

<?php
    namespace /Package3;
   use  package1/User as User1;
   use  package2/User as User2;
   class UserManager {
       public function __construct(User1 $user1, User2 $user2) {...}
       ...
   }

Upvotes: 0

Maarten Bicknese
Maarten Bicknese

Reputation: 1548

Namespaces would surely solve your problem. For example I got multiple classes named 'core', but because they're all classes of a different namespace it doesn't give any conflict at all.

This does mean you have to go over all your code and refer to the namespaced class with the correct path.

$item = new doubleClass();

would become

$item = new \my_namespace\doubleClass();

Also make sure that your other scripts don't get namespaced otherwise it wouldn't be able to find the non namespaced class anymore.

Upvotes: 1

Related Questions