您的位置:首页 > 编程语言 > PHP开发

PHP5.3+命名空间学习总结

2014-07-07 21:30 549 查看
1、namespace只对四种类型的PHP代码有影响:

Although any valid PHP code can be contained within a namespace,

only four types of code are affected by namespaces:

classes, interfaces, functions and constants.

说明:const定义的常量受到namespace的影响,而是用define()函数定义的不受影响

变量也不受影响

2、根命名空间:

默认不指定命名空间的所有代码都在跟命名空间下面,在其他命名空间中使用根下面的函数、类的时候需要使用类似\classname \functionname 这样的方式

3、命名空间之前唯一合法的代码就是declare语句。

4、命名空间声明有两种方式:一种是不使用花括号的,一种是使用的,并且两种不能交叉使用

例如:

方式一:

----------------------------------------------------

namespace test;

const ABC='abc';

function myfunction(){}

class myclass {}

namespace demo;

const ABC = 'def';

function myfunction(){}

class myclass{}

----------------------------------------------------

方式二:

---------------------------------------------------

namespace test{

const ABC='abc';

function myfunction(){}

class myclass {}

}

namespace demo{

const ABC = 'def';

function myfunction(){}

class myclass{}

}

--------------------------------------------------------

说明:在方式二中可以设置跟命名空间中的函数,使用不带命名空间名称的{}块即可

namespace {

这里写跟命名空间下面的代码

}

5、命名空间中使用函数(常量)的时候(相对路径的),函数的查询范围和顺序:【类只在当前命名空间查找】

先查找当前命名空间中是否存在函数,如果存在就使用当前命名空间下面的,如果不存在使用根目录中的

6、PHP的命名空间支持三种类型的别名或导入

PHP namespaces support three kinds of aliasing or importing:

1)aliasing a class name,

2)aliasing an interface name,

3)and aliasing a namespace name.

4))Note that importing a function or constant is not spported.

例如:

namespace foo;

use My\Full\Classname as Another;

use My\Full\NSname; // this is the same as use My\Full\NSname as NSname

7、use语法必须使用在一个文件最外层作用域上或者namespace作用域上,因为user引入的文件是在编译时候实现的,不是运行时才实现的。

The use keyword must be declared in the outermost scope of a file (the global scope) or inside namespace declarations. This is because the importing is done at compile time and not runtime, so it cannot be block scoped

8、Importing rules are per file basis, meaning included files will NOT inherit the parent file's importing rulesnamespace declarations. This is because the importing is done at compile time and not runtime,

9、解析优先级:

Class names always resolve to the current namespace name

类名总是解析到当前命名空间下

For functions and constants, PHP will fall back to global functions or constants if a namespaced function or constant does not exist.

函数和常量,如果当前命名空间下面没有找到,PHP解析器会fallbak global(向上返还到跟命名空间下)寻找
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: