Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fatal error: Cannot declare class

Tags:

php

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/site2.dev/App/rex/RexBuilder.php 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.

    <?php

namespace rex\builder;

require_once 'Router.php';

use rex\router\Router;

error_reporting(E_ALL);
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());
        }
        $router->init();
    }
}
?>

Call the class in index.php

RexBuilder::collector(array(
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

like image 750
MadLax Avatar asked Jul 03 '16 10:07

MadLax


2 Answers

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
<?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.

like image 185
Daniel Krom Avatar answered Nov 03 '22 16:11

Daniel Krom


The problem is certainly because you include the RexBuilder.php file two times instead of one.

If you call the file by this way : include('RexBuilder.php'); or this way require('RexBuilder.php'); please change it by include_once('RexBuilder.php'); or require_once('RexBuilder.php'); which only allows ONE call of the file.

like image 29
ClementNerma Avatar answered Nov 03 '22 15:11

ClementNerma