PHP5.4正式前兩天發布了,之前有看了一些PHP5.4主要特性相關文章,因此在這里小結一下。
其中好幾點更新是由Laruence貢獻的!本文部分內容也是源自Laruence的博客。
1. Buid-in web server
PHP5.4內置了一個簡單的Web服務器,這樣在做一些簡單程序就方便多了,省去了環境配置的工作,特別對于初學者來說。
把當前目錄作為Root Document只需要這條命令即可:
1 | $ php -S localhost:3300 |
也可以指定其它路徑:
1 | $ php -S localhost:3300 -t /path/to/root |
還可以指定路由:
1 | $ php -S localhost:3300 router.php |
參考:PHP: Build-in web server
2. Traits
Traits提供了一種靈活的代碼重用機制,即不像interface一樣只能定義方法但不能實現,又不能像class一樣只能單繼承。至于在實踐中怎樣使用,還需要深入思考。
官網的一個例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | trait SayWorld { public function sayHello() { parent::sayHello(); echo "World!\n" ; echo 'ID:' . $this ->id . "\n" ; } } class Base { public function sayHello() { echo 'Hello ' ; } } class MyHelloWorld extends Base { private $id ; public function __construct() { $this ->id = 123456; } use SayWorld; } $o = new MyHelloWorld(); $o ->sayHello(); /*will output: Hello World! ID:123456 */ |
參考:http://cn.php.net/manual/en/language.oop5.traits.php
3. Short array syntax
PHP5.4提供了數組簡短語法:
1 | $arr = [1, 'james' , 'james@fwso.cn' ]; |
4. Array dereferencing
1 2 3 | function myfunc() { return array (1, 'james' , 'james@fwso.cn' ); } |
我認為比數組簡短語法更方便的是dereferencing,以前我們需要這樣:
1 2 | $arr = myfunc(); echo $arr [1]; |
在PHP5.4中這樣就行了:
1 | echo myfunc()[1]; |
5. Upload progress
Session提供了上傳進度支持,通過$_SESSION["upload_progress_name"]就可以獲得當前文件上傳的進度信息,結合Ajax就能很容易實現上傳進度條了。
參考:http://www.laruence.com/2011/10/10/2217.html
6. JsonSerializable Interface
實現了JsonSerializable接口的類的實例在json_encode序列化的之前會調用jsonSerialize方法,而不是直接序列化對象的屬性。
參考:http://www.laruence.com/2011/10/10/2204.html
7. Use mysqlnd by default
現在mysql, mysqli, pdo_mysql默認使用mysqlnd本地庫,在PHP5.4以前需要:
1 | $. /configure --with-mysqli=mysqlnd |
現在:
1 | $. /configure --with-mysqli |