Duplicate Class

ID

php.duplicate_class

Severity

high

Remediation Complexity

medium

Remediation Risk

medium

Remediation Effort

medium

Resource

Reliability

Language

Php

Tags

duplicate-declaration, reliability

Description

Reports a class, interface, trait or enum whose fully-qualified name (namespace plus name) is declared more than once in the project — either in two different files or twice within the same file. The duplicate is flagged at its own location and the message names the location of the first declaration.

Rationale

PHP forbids declaring the same type twice. When both definitions are loaded the engine raises a fatal Cannot declare class …​; name is already in use error, aborting the request. Because the failure only surfaces once both files happen to be required in the same execution, a duplicate can sit unnoticed until a specific code path is exercised in production. PHP type names are case-insensitive, so User and USER in the same namespace collide.

A declaration guarded by an existence check, such as if (!class_exists('Widget')) { class Widget {} }, is a deliberate polyfill idiom and is not reported.

<?php
// file: src/Model/User.php
namespace App\Model;

class User {}                 // first declaration

// file: src/Legacy/User.php
namespace App\Model;

class User {}                 // FLAW - App\Model\User already declared in src/Model/User.php

namespace App\Domain;

class User {}                 // OK - different namespace (App\Domain\User)

if (!class_exists('App\Model\Cache')) {
    class Cache {}            // OK - guarded conditional declaration (polyfill)
}

Remediation

Keep a single canonical declaration of the type. If the two definitions are genuinely the same, delete the redundant copy and have callers reference the survivor through an autoloader. If they are different concepts that happen to share a name, move one into a distinct namespace or rename it.