gattoman
gattoman

Reputation: 65

laravel cannot declare class because the name is already in use in config file

I made config/Consts/MyConst.php

<?php                                                                                                                                                                                            

namespace App\Consts;

class MyConst
{
// some code
}

and put config/app.php

'MyConst' => App\Consts\MyConst::class,

I think this is typical const file. When I do php artisan test, I get :

PHP Fatal error: Cannot declare class App\Consts\MyConst, because the name is already in use in /Users/~~~~/config/Consts/MyConst.php on line 5

I know this error shown when I made mistake writing namespace but I can not find it.

When I use MyConst from other files such as controller or view, it works well. Only (for now) in test, this error shows. Do you have any advice ?

Upvotes: 0

Views: 3526

Answers (1)

Viduranga
Viduranga

Reputation: 520

i think if you create new class with not matching namespace, composer will throw a warning.(App\Consts,config/Consts). and 'config' area not autoload as psr-4 becouse its not defined in composer.json "autoload": area. so its better to create folder in app\Consts and put the class inside that folder.

then, create file MyConst.php and add class like below.

<?php                                                                                                                                                                                            

namespace App\Consts;

class MyConst
{
    public const EXAMPLE_CONST = 'test';
}

then, in app.php file in config folder, add your class in `aliases' section in app.php file

<?php 
...
 'aliases' => [
...
'MyConst' => App\Consts\MyConst::class,
...

run a config clear php artisan config:clear

test it, (i tested in route file)

Route::get('/testconst', function () {
    dd(MyConst::EXAMPLE_CONST);
});

enter image description here

edit: but if you need to use in a another class, you have to import class (eg: use MyConst;) first or use with slash eg: \MyConst::EXAMPLE_CONST else it will throw error.

Upvotes: 2

Related Questions