PHP namespace与use

作者: Allan_野草 | 来源:发表于2018-09-08 12:13 被阅读12次

一、namespace

what is namespace

namespace,命名空间,是为了解决项目多人协同开发,类重名冲突的问题。

两个重名的Class导入同一文件的例子:

// Allan.php
class Cat {
  public function intro() {
    echo 'i am cat of Allan';
  }
}

// Tom.php
class Cat {
  public function intro() {
    echo 'i am cat of Tom';
  }
}

// ------------------------
// test.php
require Allan.php
require Tom.php

(new Cat())->intro();// 那这个Cat到底是哪个Cat

为了解决上面的问题,namespace出现了。

How to use

把类分配到它的命名空间下面,以便区分两个类,和正常使用:

// Allan.php
namespace allan\animal;

class Cat {
  public function intro() {
    echo 'i am cat of Allan';
  }
}

// Tom
namespace tom\animal;

class Cat {
  public function intro() {
    echo 'i am cat of Tom';
  }
}

// ------------------------
// test.php
(new allan\animal\Cat())->intro();
(new tom\animal\Cat())->intro();

二、use

试想有以下场景:

namespace allan\app\class\animal\cat;
class Tiger {
  public function intro() {
    echo 'i am super cat';
  }
}

// ------------------------
// test.php
$cat = new allan\app\class\animal\cat\Cat();
$cat->intro();

命名空间太长,也不方便代码阅读。这时候,可以使用use,为上面的例子Tiger,起个别名。

在使用Tiger文件中,也就是test.php:

// test.php
use allan\app\class\animal\cat\Cat as SuperCat;// 起别名

$cat = new SuperCat();
$cat->intro();

三、总结

namespace:解决类命名重复,也可以说是类前缀
use:为名字太长的namespace,起个小名( ̄▽ ̄)"

相关文章

网友评论

    本文标题:PHP namespace与use

    本文链接:https://www.haomeiwen.com/subject/qapkgftx.html