Fatal error: Cannot declare class Error, because the name is already in use

Viewed 21326

I don't understand why my machine running PHP 7.2.9 gives this error:

Fatal error: Cannot declare class Error, because the name is already in use in controllers\error.php on line 3

I have a file named controllers/error.php which contains:

<?php

class Error {

    function __construct() {
        echo 'Error: 404 not found the file.';
    }

}

Meanwhile, I have a file named /index.php which contains:

require "controllers/error.php";
$controller = new Error;

Even if I change from require to require_once "controllers/error.php", it still keeping reporting the same message.

2 Answers

Error is a built-in class in PHP 7.

As such, you cannot make a class Error {}.

Rename the class, or put it in a namespace to avoid conflict.

(Or, as a third option, you could consider using/extending the built-in class instead of making your own error handling system from scratch.)

As already stated, 'Error' is a built in class in PHP 7. You have several options:

(1) Put your class in a namespace

<?php
namespace MyApp\Errors;
class Error {
}

Then when you use it ...

$error = new \MyApp\Errors\Error;

(2) Use a different name like AppError.

<?php
class AppError {
}

Recommended:

In general, classes should be placed into files that are the exact same name as the class itself. Class "AppError" should be in file "AppError.php"

If you are using namespaces, then the namespace should match the dir where the file is located. If you have MyApp\Errors, you would put that into "MyApp/Errors/Error.php".

class "MyApp\Errors\Error" would be in dir MyApp/Errors/Error.php.

Related