开源达人关于PHP 命名空间的一些白话。

关于命名空间:
1.php 2.php 3.php
在3.php 引入 1.php 2.php 其中两个类名相同,就会因为类名的相同而报错。解决办法:两个文件进行命名空间的命名 

namespace my1;   namespace my2; 

2.如果在3.php中我要实例化  1.php 的中类多次的话,
$a =   new a\test\Test();
$a_a = new a\test\Test();
$a_b = new a\test\Test();
虽然不报错,但是不太美观。解决办法:
use a\test\Test;
$a = new Test();
$a_a = new Test();
$a_b = new Test();
use关键字是用来引入类,用命名空间的方式表示使用了某个类。

3.如果我引入多个文件的(1.php 2.php等 )命名空间。虽然使用了命名空间,但是类名相同就会报错。这时候你就用到了as关键

字完美解决。

require_once("a.php");
require_once("b.php");
use a\test\Test;
use b\test\Test;
$a = new Test();
$b = new Test();
$a->test();
$b->test();

解决办法:
require_once("a.php");
require_once("b.php");
use a\test\Test;
use b\test\Test as BTest;
$a = new Test();
$b = new BTest();
$a->test();//页面输出:this is A class.
$b->test();//页面输出:this is B class.
as关键字是对类名称定义别名,可以有效防止类名称相同冲突 

4.没有命名空间的叫做全局类,如果要使用需要类前面加入反斜杠”\” 比如我们在a.php同级再建立一个全局类文件:c.php:

class Test{

 public function test()

  {

   echo "this is C class.";

  }

}

在index.php文件中这样做即可调用c.php中的test方法

require_once("a.php");
require_once("b.php");
require_once("c.php");

//页面输出:this is C class.
use a\test\Test;
use b\test\Test as BTest;
$a = new Test();
$b = new BTest();
$c = new \Test();
$a->test();//页面输出:this is A class.
$b->test();//页面输出:this is B class.
$c->test();//页面输出:this is C class.

5.将全局的非命名空间中的代码与命名空间中的代码组合在一起,只能使用大括号形式的语法。

<?php
namespace MyProject {

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }
}

namespace {    // 全局代码
session_start();
$a = MyProject\connect();
echo MyProject\Connection::start();
}
?>

6.在声明命名空间之前唯一合法的代码是用于定义源文件编码方式的 declare 语句。所有非 PHP 代码包括空白符都不能出现在命

名空间的声明之前。declare(encoding='UTF-8'); 

<?php
declare(encoding='UTF-8'); //定义多个命名空间和不包含在命名空间中的代码
namespace MyProject {

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }
}

namespace { // 全局代码
session_start();
$a = MyProject\connect();
echo MyProject\Connection::start();
}
?>


7.const用于类成员变量 和 普通全局常量 define('ABC',"这个是普通全局常量");
类常量

<?php
namespace a;
const LCL = "这是类常量";

define("QJCL","这是全局常量");
namespace b;

echo \a\LCL;
echo \a\QJCL; //这是全局常量。

发表评论