我们可以通过两种方式解决命名空间问题
第一种方式(Namespace和require)方式
Class1.php (Timer Class)
namespace Utility;
class Timer
{
public static function {}
}
Class2.php (Verification Class)
namespace Utility;
require "Class1.php";
//Some interesting points to note down!
//We are not using the keyword "use"
//We need to use the same namespace which is "Utility"
//Therefore, both Class1.php and Class2.php has "namespace Utility"
//Require is usually the file path!
//We do not mention the class name in the require " ";
//What if the Class1.php file is in another folder?
//Ex:"src/utility/Stopwatch/Class1.php"
//Then the require will be "Stopwatch/Class1.php"
//Your namespace would be still "namespace Utility;" for Class1.php
class Verification
{
Timer::somefunction();
}
第二种方式(使用Composer和自动加载方式)
Make composer.json file. According to your example “src/Utility”
We need to create a composer.json file before the src folder. Example: In a folder called myApp you will have composer.json file and a src folder.
{
"autoload": {
"psr-4": {
"Utility\\":"src/utility/"
}
}
}
现在转到该文件夹打开您的终端,在文件夹位置有composer.json文件.现在输入终端!
composer dump-autoload
这将创建供应商文件夹.因此,如果您有一个名为“MyApp”的文件夹
你会看到vendor文件夹,src文件夹和composer.json文件
Timer.php(Timer Class)
namespace Utility;
class Timer
{
public static function somefunction(){}
}
Verification.php (Verification Class)
namespace Utility;
require "../../vendor/autoload.php";
use Utility\Timer;
class Verification
{
Timer::somefunction();
}
当你有一个复杂的文件夹结构时,这个方法更强大!!