php 命名空间(namespace)原理与用法实例小结

yipeiwu_com6年前PHP代码库

本文实例讲述了php 命名空间(namespace)原理与用法。分享给大家供大家参考,具体如下:

命名空间一个最明确的目的就是解决重名问题,PHP中不允许两个函数或者类出现相同的名字,否则会产生一个致命的错误。这种情况下只要避免命名重复就可以解决,最常见的一种做法是约定一个前缀,也可以采用命名空间的方式解决

TestSpace.php

<?php
namespace Demo\Test;    //声明一个命名空间Demo
class Test1
{
  static function test()
  {
    return "my class name demo1";
  }
  function test1()
  {
    return "2222222222222222222B";
  }
}

模式一 直接实例该类

index1.php

require("TestSpace.php");
$ms1 = new \Demo\Test\Test1();
echo $ms1->test1() . "<br />\n";
echo \Demo\Test\Test1::test();

模式二 use 载入该类

index2.php

require("TestSpace.php");
use Demo\Test\Test1;  //导入命名空间Demo\Test下的Tese1类
$ms2 = new Test1();
echo $ms2->test1() . "<br />\n";
echo Test1::test();

模式三 use载入命名空间

index3.php

use Demo\Test;     //载入命名空间Demo\Test 这一层级
$ms3 = new Test\Test1();
echo $ms3 ->test1() . "<br />\n";
echo Test\Test1::test();

模式四

index4.php

use Demo\Test as test;
$ms3 = new test\Test1();
echo $ms3 ->test1() . "<br />\n";
echo test\Test1::test();

至此 thinkphp 3.2版本中我们看到的

namespace Home\Controller;
use Think\Controller;

namespace 声明的是该文件的命名空间;

use 载入在Think命名空间下的Controller 类

tip : Controller 类 位于 Thinkphp/Library/Think/Controller.class.php

相关文章

PHP生成随机码的思路与方法实例探索

本文实例讲述了PHP生成随机码的思路与方法。分享给大家供大家参考,具体如下: 背景 今天因为无聊,小伙伴让写一个生成5位随机码的函数,要求:可包含数字、字母大小写,代码尽量短。 解题思路...

redis查看连接数及php模拟并发创建redis连接的方法

max_redis.php <?php set_time_limit (0); for($i=1;$i<=1050;$i++){ exec("nohup p...

PHP设计模式之装饰器模式定义与用法详解

本文实例讲述了PHP设计模式之装饰器模式定义与用法。分享给大家供大家参考,具体如下: 什么是装饰器模式 作为一种结构型模式, 装饰器(Decorator)模式就是对一个已有结构增加"装饰...

PHP 开发者该知道的 5 个 Composer 小技巧

Composer 是新一代的PHP依赖管理工具。其介绍和基本用法可以看这篇《Composer PHP依赖管理的新时代》。本文介绍使用Composer的五个小技巧,希望能给你的PHP开发带...

php中curl、fsocket、file_get_content三个函数的使用比较

抓取远程内容,之前一直都在用file_get_content函数,其实早就知道有curl这么一个好东西的存在,但是看了一眼后感觉使用颇有些复杂,没有file_get_content那么简...