1.2.725. Multiple Class Declarations

It is possible to declare several times the same class in the code. PHP will not mention it until execution time, since declarations may be conditional.

It is recommended to avoid declaring several times the same class in the code. The best practice is to separate them with namespaces, they are for here for that purpose. In case those two classes are to be used interchangeably, the best is to use an abstract class or an interface.

<?php

$a = 1;

// Conditional declaration
if ($a == 1) {
    class foo {
        function method() { echo 'class 1';}
    }
} else {
    class foo {
        function method() { echo 'class 2';}
    }
}

(new foo())->method();
?>

See also class.

1.2.725.1. Suggestions

  • Store classes with different names in different namespaces

  • Change the name of the classes and give them a common interface to allow from common behavior

1.2.725.2. Specs

Short name

Classes/MultipleDeclarations

Rulesets

All, Analyze, CE, CI-checks

Exakat since

0.8.4

PHP Version

All

Severity

Major

Time To Fix

Quick (30 mins)

Precision

Very high

Features

class

Available in

Entreprise Edition, Community Edition, Exakat Cloud