php 命名空间详解

众所周知 命名空间 是php5.3 带来的新特性 可以帮我们解决在工程量大时 类命名重复的问题 下面 我就来分享一下 我对命名空间的理解

首先我们创建三个php文件在同一个文件夹 分别为 index.php test1.php test2.php

test1.php 的内容如下



class  test
{
    function say()
    {
        echo 'this is test1 ';
        echo "
"
; } }

test2.php 的内容如下



class test
{
    function say()
    {
        echo 'this is test2 ';
        echo "
"
; } }

index.php 的内容如下



require_once('test1.php');
require_once('test2.php');

现在当我们调用 index.php 时我们会发现一个错误

php 命名空间详解_第1张图片

php提示我们不能声明 test2.php 的 test类


这是为什么呢 其实是因为 test2.php 中的 test类 和 test1.php 中的类重名了 系统不知道该调用哪一个

正是为了解决这一个问题 所以 php5.3 引入了 命名空间这一新特性

现在我们为 test1.php 加上命名空间



namespace space\test1;

class  test
{
    function say()
    {
        echo 'this is test1 ';
        echo "
"
; } }

同理 test2.php


namespace space\test2;
class test
{
    function say()
    {
        echo 'this is test2 ';
        echo "
"
; } }

现在我们在调用 index.php 我们就会发现错误不见了


这是为什么呢 其实是因为 我们加了 namespace 命名空间以后 系统会自动识别 test1.php 的test类 是space\test1里面的 而test2.php 的test类 是space\test2里面的 他们是不同的


下面我们在 index.php 里加上几行代码测试一下



require_once('test1.php');
require_once('test2.php');

$test1 = new \space\test1\test();
$test2 = new \space\test1\test();

$test1->say();
$test2->say();


运行后得到

php 命名空间详解_第2张图片


我们会发现 运行完美成功


但是每次 初始化 new 一个实例出来的时候 我们都要 写上 $test1 = new \space\test1\test(); 这样的一大长串 是不是有一点不够简洁 正是因为这个原因 php 又为我们 提供了 use 关键字

use 的作用是设定我们默认使用的命名空间



require_once('test1.php');
require_once('test2.php');

use space\test1\test;

$test1 = new test();
$test1->say();



然后 我们在 访问 index.php


php 命名空间详解_第3张图片

完美 果然 把 test1.php 中的 test类 给实例化出来了


这时候 想必 肯定 会有人 问 那 test2.php 中的 test类 我们怎么实现出来呢


是像下面这样来实现吗

php 命名空间详解_第4张图片

大家光看照片 就知道 肯定不能 这样来实现了 因为编译器 已经报错了


因为这样的话 系统又会像没有加命名空间一样 不知道该调用哪一个 test类了


为了 解决 这个问题 所以 php 又给我们 推出了 一个 和 use 关键字连用的关键字 as


as的用法是为命名空间取一个别名



require_once('test1.php');
require_once('test2.php');

use space\test1\test;
use space\test2\test as test2;

$test1 = new test();
$test2 = new test2();

$test1->say();
$test2->say();

现在我们在调用 index.php

php 命名空间详解_第5张图片

完美运行

你可能感兴趣的:(php)