PHP5.3新特性之命名空间

 
PHP5.3新特新之命名空间详细说明。
命名空间(Namespaces)

* PHP5.3最大的新功能
* 完全支持名字空间特征
* 大部分的功能的执行在编译时
* 简化命名惯例

1) 更清晰的代码

不使用 Namespaces
function MY_wrapper() {}
class MY_DB {}
define('MY_COMM_STR', '');
   
MY_wrapper();
new MY_DB();
MY_COMM_STR;

2) 使用 Namespaces
namespace MY;
   
function wrapper() {}
   
class DB { }
   
const CONN_STR = '';
   
   
use MY AS MY;
   
wrapper();
   
new DB();
   
CONN_STR;

3) 一个文件中多个名字空间
namespace LIB;
   
class MYSQL {}
class SQLite {}
   
$b = new SQLite(;
   
namespace LIB_EXTRA;
   
class MScrypt {}
   
$a new MScrypt();
   
var_dump(
get_class($a),
get_class($b)
};
   
// result:
// string(18) "LIB_EXTRA::MScrypt"
// string(11) "LIB::SQLite"

4) 名字空间的层级
namespace foo;
   
function strlen($foo) { return htmlspecialchars($foo); }
   
echo strlen("test"); // test
echo ::strlen("test") // 4
echo namespace::strlen("test"); // test

* function, class 和 constant 引用在一个名字空间中首先指向这个名字空间, 其次才是一个全局的范围


5) 名字空间 & 自动引入
function __autoload($var) { var_dump($var); } // LIB::foo
require "./ns.php";
/**
<?php
namespace LIB;
new foo();
?>
*/

* __autoload() 将处理为和名字空间的类名一起。
* autoload 仅在 class 不在名字空间和全局范围内存在时触发。
* __autoload() 声明在一个名字空间中将不别调用!




6) 其他的名字空间的语法技巧
namespace really::long::pointlessly::verbose::ns;
   
__NAMESPACE__; // 当前的名字空间名称
   
class a {}
   
get_class( new a() ); // really::long::pointlessly::verbose::ns::abs
   
use really::long::pointlessly::verbose::ns::a AS b; // 从一个名字空间引用class

你可能感兴趣的:(PHP5.3新特性之命名空间)