Fatal error: Cannot redeclare class className in: How to fix?

Fatal error: Cannot redeclare class className in.., Error comes when PHP process have duplicate class name in files and both files or class include/import in process.

When PHP gives Fatal error: Cannot redeclare class className in.., How to handle it?

First things comes to developer mind is, If i can un-declare or remove or exclude previous class file from process, issue will fix. Un-declare or remove previously included file or class not possible so its not proper solution.

Let’s check how to fix duplicate class name issue in PHP with detail and reason why some of our quick fix ideas not work for it.

Fatal error: Cannot redeclare class
Fatal error: Cannot redeclare class

Use Namespace for fix Fatal error: Cannot redeclare class error

PHP namespaces allows same class name in different namespace. e.g., if we create 2 files with different namespace and same class name and use class in process, it will works fine.

Let’s check process by example:

File 1: firstClass.php : first file with class that will duplicate in second file.


<?php namespace first;
    class duplicate { 
        public static function helo() {
            echo 'hello';
        }
    }
?>

File 2: secondClass.php : second file with different namespace and same class name.


<?php namespace second;
    class duplicate { 
        public static function helo() {
            echo 'hello';
        }
    }
?>

Now use both class in same process.


<?
include_once 'firstClass.php';
include_once 'secondClass.php';

use first as firstNs;
use second as secondNs;

echo firstNs\duplicate::hello();
echo secondNs\duplicate::hello();

?>

Example given for use name space with duplicate class and static methods, if you have non static method, here you need some change to create class object and access it by ->.

Un-declare or unset previously included duplicate class:

This is first idea when we face PHP gives Fatal error: Cannot redeclare class. PHP not gives such option to un-declare or remove included file from process, so need to forget this idea 🙂

For fix duplicate class error you can try above given namespaces solution.

If possible in programming, try to give unique class name to avoid such fatal errors.

Hope given solution is helpful for your problem, If you like and found post helpful, please share with other friends and PHP programmers 🙂