php5.4 新特性

trait 是php新的一种特质,可以解决多重继承

<?php
trait C {
    public function say() {
        parent::say();
        echo " {$this->_id}\n";
    }
}
trait D {
    public function say2() {
        parent::say();
        echo " 2\n";
    }
}

class A {
    public function say() {
        echo "Hello";
    }
}
class B extends A {

    private $_id;

    public function __construct() {
        $this->_id = '1';
    }

    use C,D;
}
(new B)->say();
(new B)->say2();

数组的短语法

<?php
$test = [
    'a' => 'A',
    'b' => 'B',
];
var_dump($test);
foreach([1,2,3,4] as $val) {
    var_dump($val);
}

变量的二进制表达

<?php

$x = 0b0001;
$y = 0b0010;
var_dump($x | $y);
var_dump($x & $y);
var_dump($x ^ $y);

支持Class::{expr}()语法

<?php

class A {
    public function say() {
        echo "hello world!\n";
    }
}

(new A)->{'say'}();

闭包支持$this

<?php

class A {
    private $_id;

    public function __construct() {
        $this->_id = 15;
    }

    public function say($x) {
        $func = function($y) use ($x) {
            echo $this->_id * $y * $x;
        };
        echo "hello";
        echo $func(2);
        echo "\n";
    }
}

(new A)->{'say'}(2);

数组的非关联化

<?php

function a() {
    return [1,2,3,4,5];
}

echo a()[4];

Callable typehint

<?php
class Human {

    private $_name;
    public function __construct($name) {
        $this->_name = $name;
    }

    public function hello() {
        echo "{$this->_name} hello\n";
    }
}

function hi(callable $f) {
    $f();
}

hi([new Human("Gonzalo"), 'hello']);
comments powered by Disqus
Table of Contents