首页 > Other > Php 5.3 新特性代码说明

Php 5.3 新特性代码说明

引入 __DIR__ magic常量 定位脚本的目录

1 echo __DIR__."|".dirname(__FILE__);

允许从2个值的or/and表达式快速的获取一个非空的值

1 echo (1 ?: 0) ."|". ("" ?: 0)."|". var_export(array() ?: array(1), true);

类添加__callStatic方法,等价于 __call(),但它是为调用静态方法准备的

01 class xxx{
02 function __call($func, $args){
03 echo "function name:".$func;
04 echo "";
05 echo "args:".var_export($args, true);
06 }
07 static function __callStatic($func, $args){
08 echo "static function name:".$func;
09 echo "";
10 echo "static args:".var_export($args, true);
11 }
12 }
13 $x = new xxx();
14 $x->testfunc("oo");
15 echo "";
16 xxx::teststatic("xx");

动态的调用静态的方法

1 class xx{
2 static function test(){
3 echo __METHOD__;
4 }
5 }
6 $c = "xx";
7 $m = "test";
8 $c::$m();

延迟静态绑定(静态处理从编译时延迟到执行时)

01 class A{
02 static function whoami(){
03 echo __CLASS__;
04 }
05
06 static function say1(){
07 self::whoami();
08 }
09
10 static function say2(){
11 static::whoami();
12 }
13 }
14
15 class B extends A{
16 static function whoami(){
17 echo __CLASS__;
18 }
19 }
20
21 class C extends A{
22 static function whoami(){
23 echo __CLASS__;
24 }
25 }
26
27 B::say1();
28 C::say2();

MySQLnd

INI Magic

扩展的 OpenSSL 函数

SPL优化

时间处理进行扩展了和添加

1 $date = strtotime("11-05-17 00:00:00");
2 echo date("Y-m-d", $date)."|";
3
4 $date = date_create_from_format("y-m-d", "11-05-17");
5 echo $date->format("Y-m-d");

垃圾回收器(为复杂和长时间运行脚本的执行结束周期释放内存的清理)

1 gc_enable(); // 允许垃圾回收
2 var_dump(gc_enabled()); // true
3 var_dump(gc_collect_cycles()); // 某个元素的清理
4
5 gc_disable(); // 禁止垃圾回收

NOWDOC(不对HEREDOC进行转译)

1 $fubar = "xxx";
2 $xbar = <<<ONE
3 this is HEREDOC $fubar
4 ONE;
5
6 $abar = <<<'TWO'
7 this is NOWDOC $fubar
8 TWO;
9 echo $xbar."|".$abar;

匿名函数体验

1 $ofun = create_function('$a, $b', 'return $a*$b;'); //不要忘了分号,传统方法
2 echo $ofun(2, 5);
3 $nfun = function ($a, $b){
4 return $a*$b;
5 };//不要忘了分号,现代方法
6 echo $nfun(3, 5);

闭包体验

01 $arr = array(1, 2, 3, 5, 6, 7);
02 $res = array_filter($arr, function($v) { return $v >4; });
03 var_dump($res);
04
05 function countnum(){
06 $num = 0;
07 $testt = function() use(&$num){
08 ++$num;
09 echo $num;
10 };
11 return $testt;
12 }
13 $t = countnum();
14 $t();
15 $t();

命名空间

01 namespace xxx; //第一个namespace需要在所有输出之前
02 function t(){
03 return __NAMESPACE__;
04 }
05
06 namespace xxx;
07 function t(){
08 return __NAMESPACE__;
09 }
10 echo \xx\t()."|";
11 echo \xxx\t();
分类:Other
  1. 还没有评论。
  1. No trackbacks yet.

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s

%d 博主赞过: