php找不到类,使用命名空间时找不到PHP类

我们可以通过两种方式解决命名空间问题

第一种方式(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();

}

当你有一个复杂的文件夹结构时,这个方法更强大!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值