Error: Cannot redeclare class becuase of entity self reference I've got 2 problems here. 

I have an entity that references itself in field definition (see below). 

Problem No.1. I've got a fatal error 
PHP Fatal error:  Cannot redeclare class Drupal\mymodule\MyEntity when trying to install the module.

Problem No.2 I now get it every time even when I remove the referencing field and do drush cr unless I wrap the class definition in !class_exists().

I swear this is the only file defining the class.

Is there a way to clean this out of wherever drupal has stored it?

And how do I declare this type of self-reference?

&lt;?php

namespace Drupal\mymodule;

use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;

/**
 * @ContentEntityType(
 *     id = "myentity",
 *     label = "My Entity",
 *     base_table = "myentity"
 * )
 */
class MyEntity extends ContentEntityBase
{
    public static function baseFieldDefinitions(EntityTypeInterface $entity_type)
    {
        $fields = [];

        // Standard field, used as unique if primary index.
        $fields['id'] = BaseFieldDefinition::create('integer')
            -&gt;setLabel(t('ID'))
            -&gt;setReadOnly(true);

        $fields['myentity_id'] = BaseFieldDefinition::create('entity_reference')
            -&gt;setTargetEntityTypeId('myentity');

        $fields['name'] = BaseFieldDefinition::create('string');

        return $fields;
    }
}
Ok so the problem was in the namespace:

namespace Drupal\mymodule;


From my observation (can't find this in the Entity API documentation entities are supposed to be placed in the src/Entity (which I did) which imposes the Entity namespace. So fixing the namespace solved my issue.

namespace Drupal\mymodule\Entity;


What a stupid way to spend a half of a day. Looks like I'm too used to class loaders that will simply not find the class if you place it in the wrong directory.