MadLax MadLax - 1 year ago 223
PHP Question

Fatal error: Cannot declare class

I can not understand why php gives me an error

"Fatal error: Cannot declare class rex\builder\RexBuilder, because the
name is already in use in /var/www/ on
line 12"

RexBuilder static class, and it is called only 1 time.
I did a search on the project, no longer classes with the same name.


namespace rex\builder;

require_once 'Router.php';

use rex\router\Router;

ini_set('display_errors', 1);

class RexBuilder {

public static function collector($array) {
$router = new Router();
foreach ($array as $key => $val) {
$router->get($val->getMethod(), $val->getInterfaces(), $val->getHandler());

Call the class in index.php

new BuildModel('POST', '/api/v1/user/register', new \api\register\Registration()),
new BuildModel('POST', '/api/v1/user/login', new \api\login\Login())));

More This class is not used

Answer Source

The error is thrown because of the use rex\router\Router; duplicate classes.

When you are writing use namespace.. it means you can go directly to that namespace like it is your current namespace

Lets take a look at the next code:

We'll create a file and declare that it belongs to namespace classes\a

//file: a.php

namespace classes\a;

class A{


now lets create another file b.php (and declare it belongs to namespace classes\b but it means nothing for the example)

namespace classes\b;

require_once "a.php";

use classes\a; //Notice that I'm using this namespace, it means I can use it directly

class A{


Generates the error

Fatal error: Cannot declare class classes\b\A because the name is already in use in

We have to solutions possible:

First: remove the use tag and write the namespace directly

class A{
    function __constructor(){
        $instance = new classes\a\A();

Second, give it alias

use classes\a as out_a;

class A{
    function __constructor(){
        $instance = new out_a\A();

For your code, just remove the use or give it an alias.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download