PHP 5.4 新特性

精简数组用法

//old
$num = array('one', 'two', 'three');
//new
$num = ['one', 'two', 'three'];
$num = [
    '1'=>'one',
    '2'=>'two',
    '3'=>'three'
];

数组成员访问

$name = explode(",", "David, Beckham")[0];

function test()
{
    return [
        'key'  => [ 'hello'  =>  'world' ]
    ];
}
echo  test()[ 'key' ][ 'hello' ];

Trait
Traits 是一种轻量级的方法复用。

trait cURL
{
    public function curl($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);

        return $output;
    }
}

/*
 * Twitter API Class
 */
class Twitter_API
{
    use cURL;

    public function get($url)
    {
        return json_decode($this->curl("http://api.twitter.com/".$url));
    }
}

/*
 * Facebook API Class
 */
class Facebook_API
{
    use cURL;

    public function get($url)
    {
        return json_decode($this->curl("http://graph.facebook.com/".$url));
    }
}

发表评论