命名空间

1. 什么是命名空间?

  从广义上来说,命名空间是一种封装事物的方法。在很多地方都可以见到这种抽象概念。例如,在操作系统中目录用来将相关文件分组,对于目录中的文件来说,它就扮演了命名空间的角色。具体举个例子,文件 foo.txt 可以同时在目录/home/greg/home/other 中存在,但在同一个目录中不能存在两个 foo.txt 文件。另外,在目录 /home/greg 外访问 foo.txt 文件时,我们必须将目录名以及目录分隔符放在文件名之前得到 /home/greg/foo.txt。这个原理应用到程序设计领域就是命名空间的概念。

2. 命名空间的作用?

  ①用户编写的代码与PHP内部的类/函数/常量或第三方类/函数/常量之间的名字冲突。

  ②为很长的标识符名称(通常是为了缓解第一类问题而定义的)创建一个别名(或简短)的名称,提高源代码的可读性。

3. 如何定义命名空间?

  命名空间通过关键字namespace 来声明。如果一个文件中包含命名空间,它必须在其它所有代码之前声明命名空间。

  eg:

 1 <?php
 2 
 3 namespace yss\test;
 4 
 5 class VipCard
 6 {
 7     public function foo()
 8     {
 9         echo "this is a test";
10     }
11 }      
12 
13 ?>

4. 如何使用命名空间?

  eg:比如我在同一个目录下新建了两个php文件,test1.class.php, test2.php, 其中test1.class.php 中用了命名空间,然后我在test2.php中调用test1.class.php中的类。

 1 <?php
 2 
 3 // test1.class.php
 4 
 5 namespace yss\test;
 6 
 7 class VipCard
 8 {
 9     public function foo()
10     {
11         echo "this is a test";
12     }
13 }      
14 
15 ?>

 

 1 <?php
 2 
 3 // test2.php
 4 require './test1.class.php';
 5 
 6 //$testObj = new VipCard();    // Fatal error: Class 'VipCard' not found in
 7 $testObj = new yss\test\VipCard();    // ok
 8 $testObj->foo();    
 9     
10 ?>

 

5. 操作符use的使用方法?

  使用use操作符导入、使用别名

<?php

// test2.php
require './test1.class.php';

use yss\test\VipCard;

$testObj = new VipCard();    // ok
//$testObj = new yss\test\VipCard();    // ok
$testObj->foo();     
    
?>

 

  

posted @ 2014-11-20 22:37  yangss001  阅读(318)  评论(0编辑  收藏  举报