命名空间与自动加载系列(五)--use使用与冲突的解决

作者: 温新

分类: 【PHP基础】

阅读: 2118

时间: 2021-05-17 11:26:11

use引入命名空间

命名空间与自动加载系列(三)--命名空间的使用 这篇文章中学习的命名空间的使用。仔细看看会发现使用的是include引入文件,而后再使用。现在有一个更好的方法来解决,就是使用use关键字引入命名空间。

现在来改造案例:

// Post.php

<?php

namespace App\Controller;

class Post
{
	public static function index()
	{
		echo __METHOD__ . PHP_EOL;
	}
}
// index.php
<?php

namespace App;

use App\Controller\Post;

class Index
{
	public static function index() 
	{
		echo __METHOD__ . PHP_EOL;
	}
}

Post::index();

同理,多个类的引入与使用也是如此。

使用别名解决冲突

继续使用之前的laravel目录为例,新建文件Module/Post.php

// Module/Post.php

<?php

namespace App\Moduel;

class Post
{
	public static function index()
	{
		echo __METHOD__ . PHP_EOL;
	}
}

现在我们在index.php使用该类

<?php

namespace App;
use App\Controller\Post;
use App\Module\Post as A;

include './Post.php';
include './Module/Post.php';

class Index
{
	public static function index() 
	{
		echo __METHOD__ . PHP_EOL;
	}

// Post::index();
A::index();

使用别名解决冲突问题。

2021-05-16

请登录后再评论