Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined constant error when using namespace in Symfony

PHP 5.6 Symfony 3

I have a file in a bundle that contains a namespace with defined constants...

constfile.php

<?php
namespace Some\Interesting\ConstFile {
    const NAME_OF_CONSTANT = 'Some Constant';
}
namespace Some\Interesting\ConstFile\Specific {
    const NAME_OF_SPECIFIC_CONSTANT = 'Some Specific Constant';
}

Then I have another file in another bundle which I'm trying to use the constants...

stuff.php

<?php
namespace More\Cool\Stuff;

use Some\Interesting\ConstFile as CF;
use Some\Interesting\ConstFile\Specific as CFS;

class Stuff {
    public function doit() {    
        $output->writeln(CF\NAME_OF_CONSTANT);
        $output->writeln(CFS\NAME_OF_SPECIFIC_CONSTANT);
    }
}

PHPStorm doesn't have any complaints with this set up. However, when I run this, I'm getting a 'Fatal error: Undefined constant NAME_OF_CONSTANT in stuff.php' error.

like image 774
Tim Avatar asked Oct 21 '25 12:10

Tim


2 Answers

This error could also happen when you mistake and prefix your namespace with an anti slash. Use statements can be prefixed by \, namespace can not. A leading anti slash in namespace is causing php to understand the whole line as constant.

like image 54
extrablind Avatar answered Oct 23 '25 04:10

extrablind


The auto-load does not work well when try to load this type of files, try including the original file manually.

require 'path/to/constfile.php'
like image 20
rafrsr Avatar answered Oct 23 '25 02:10

rafrsr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!