Magento – Cannot declare interface , because the name is already in use

fatal errormagento2setup-di-compile

After creating a simple interface in my new module. I typed in bin/magento setup:di:compile, and I get an error saying that the name is already in use.

Here is my code:

namespace Company\Test\Api;

/*
 *  @api
 */
interface XyzInterface {
    public function getSomething();
}

Then I get this error:

Repositories code generation... 1/7 [====>-----------------------]  14% 2 secs 52.0 MiBPHP 
Fatal error:  Cannot declare interface Company\Test\Api\XyzInterface, because the name is already in use in .../app/code/Company/Test/Api/XyzInterface.php on line 13

The line is the "interface XyzInterface"
I am not sure what I am doing wrong.

Best Answer

Today I received the same-type error:

PHP Fatal error: Cannot declare class Class\Name\Here , because the name is already in use in /var/www/m2/magento2/app/code/path/to/the/class.php on line 100

where the line 100 is end of the file.

Approximately after 4 hours of debugging I really find the reason: a misprint in the namespace declaration. Till the final moment I didn't believe that it is a typographical error in names declaration, but when I have rewritten all names anew - the mistake has disappeared. This article was very helpful:

I’ll scratch my head for a while, wonder what’s going on, and eventually realize it’s this

Pulsetorm

i.e. I’ve mistyped a namespace name, and when the initial autoloads loads the class file, it won’t have defined the class it’s looking for, and then a second autoloader (Composer’s usually) loads it again, and tries to redefine the same incorrect class.

i.e., Magento wanted the class

Pulsestorm\Helloworld\Observers\Block

but I defined

Pulsetorm\Helloworld\Observers\Block

thanks to the wrong namespace.

Thank you, Alan Storm :)

UPDATE:

Another type of that error is incorrect Namespace declaration with missing part of the namespace, as in this example:

Error:

Repositories code generation... 1/7 [====>-----------------------] 14% 1 sec 50.0 MiBPHP Fatal error: Cannot declare class Migration\Step\Version11410to2000Test, because the name is already in use in /var/www/vhosts/rwld/vendor/magento/data-migration-tool/tests/unit/testsuite/Migration/Step/UrlRewrite/Version11410to2000Test.php on line 109

where the line 109 is end of the file.

In the file vendor/magento/data-migration-tool/tests/unit/testsuite/Migration/Step/UrlRewrite/Version11410to2000Test.php we found the namespace as Migration\Step when the correct namespace should be Migration\Step\UrlRewrite because path to this class is Migration/Step/UrlRewrite. After changing of the namespace to Migration/Step/UrlRewrite the error is gone.