命名空间与自动加载系列(五)--use使用与冲突的解决
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
请登录后再评论