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

<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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值