Field formatter module throws cannot declare class error I am trying to write a custom module, which defines a field formatter plugin, but when I visit the Manage display page, I get this error:


  Fatal error: Cannot declare class Drupal\my_formatter\Plugin\Field\FieldFormatter\MyFormatter, because the name is already in use in /var/www/sites/drupalroot/web/modules/custom/my_formatter/src/Plugin/Field/FieldFormatter/MyFormatter.php on line 0


I've compared my module to several other working field formatter plugins and can't seem to figure out what I'm missing.

My module directory is laid out like this:

web/modules/custom/my_formatter/
├── my_formatter.info.yml
├── my_formatter.module
├── src
│   └── Plugin
│       └── Field
│           └── FieldFormatter
│               └── MyFormatter.php
└── templates
    └── my-formatter.html.twig


My info file:

name: My Formatter
type: module
description: 'Do some fun stuff.'
package: Field types
core: 8.x
dependencies:
  - field
  - file


And my MyFormatter.php file:

&lt;?php
/**
 * @file
 * Contains \Drupal\my_formatter\Plugin\Field\FieldFormatter\MyFormatter.
 */

namespace Drupal\my_formatter\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\file\Plugin\Field\FieldFormatter\FileFormatterBase;

/**
 * Plugin implementation of the 'my' formatter.
 *
 * @FieldFormatter(
 *   id = "my",
 *   label = @Translation("My Formatter"),
 *   field_types = {
 *     "file"
 *   }
 * )
 */
class MyFormatter extends FileFormatterBase {

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];
    foreach ($items as $delta =&gt; $item) {
      $elements[$delta] = [
        '#theme' =&gt; 'my_formatter',
        '#my_var' =&gt; 'Hello',
      ];
    }
    return $elements;
  }

}


Any help would be greatly appreciated.
Here are some pointers that might help:


Run drush cr to clear cache and see if the error persists.
Enable error backtraces from the Config &gt; Development &gt; Logging &amp; Errors page to see if you get more info in the error message about where the class is being redeclared.
Search your project for the name MyFormatter and see if you find anything besides the MyFormatter.php file you've mentioned.
File, directory and class names are case-sensitive – in what you've shared, they seem to be correctly named.
Make sure you're not manually using require or include anywhere to include this file.


Probably, not applicable in your case.