Home > Net >  Cannot import namespace by using the USE
Cannot import namespace by using the USE

Time:11-01

I have three files firstFile.php, secondFile.php, and thirdFile.php.

firstFile looks like the below:

namespace test\main;

function hello () {
   echo 'from main';
}

secondFile looks like the below:

namespace test\second;

function hello () {
   echo 'from second';
}

thirdFile looks like the below:

use function test\main\hello;

echo hello();

My question is why use function test\main\hello; is working but when I use use function test\second\hello;, it then causes a fatal error: Uncaught Error: Call to undefined function test\second\hello()?

CodePudding user response:

If you use all function in one file, it will with errors. Because all the content of files contain hello function. However, you need to use autoload.php or custom autoload schema. Otherwise, you may use require or include all this files before their using.

For example

require "firstFile.php"
require "secondFile.php"

use function test\main\hello;
use function test\second\hello as secondHello;

echo hello();
echo secondHello();

  • Related