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

yipeiwu_com7年前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 函数中使用static的说明

复制代码 代码如下: function sendHeader($num, $rtarr = null) { static $sapi = null; if ($sapi === null...

php实现word转html的方法

本文实例讲述了php实现word转html的方法。分享给大家供大家参考,具体如下: 要想完美解决,office转pdf或者html,最好还是用windows office软件,libre...

PHP排序算法系列之桶排序详解

桶排序 桶排序(Bucket sort)或所谓的箱排序,是一个排序算法,工作的原理是将数组分到有限数量的桶里。每个桶再个别排序(有可能再使用别的排序算法或是以递归方式继续使用桶排序进行排...

PHP中feof()函数实例测试

本文实例讲述了PHP中的feof()函数的用法,针对feof()函数进行了一定的测试,很有实用价值。具体分析如下: 本文实例运行环境: OS:Mac OS X 10.8.4 PHP:5....

浅析php学习的路线图

浅析php学习的路线图

1.php初级教程 初级教程主要的页面设置的,就是 html+js+div+css2.中级教程 中级的话开始接触php,就是php核心编程和数据库的交互3.高级课程 这个主要...