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;
namespace MY;
function wrapper() {}
class DB { }
const CONN_STR = '';
use MY AS MY;
wrapper();
new DB();
CONN_STR;
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"
namespace foo;
function strlen($foo) { return htmlspecialchars($foo); }
echo strlen("test"); // test
echo ::strlen("test") // 4
echo namespace::strlen("test"); // test
5) 名字空间 & 自动引入
function __autoload($var) { var_dump($var); } // LIB::foo
require "./ns.php";
/**
<?php
namespace LIB;
new foo();
?>
*/
* 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
<script type="text/javascript"> document.body.oncopy = function () { setTimeout( function () { var text = clipboardData.getData("text"); if (text) { text = text + "/r/n本篇文章来源于 PHP资讯 原文链接:"+location.href; clipboardData.setData("text", text); } }, 100 ) } </script>