0

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 ?

3
  • config/Consts/MyConst.php is not App\Consts Commented Sep 14, 2021 at 15:51
  • 'MyConst' => \App\Consts\MyConst::class and php artisan config:cache should work Commented Sep 14, 2021 at 16:04
  • Hi nice_dev. Thanks. I tried php artisan config:cache, then i got same error "Cannot declare class~~~~" Commented Sep 14, 2021 at 23:47

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.