面向?qū)ο缶幊?/h1>
Buid-in web server內(nèi)置了一個(gè)簡(jiǎn)單的Web服務(wù)器

把當(dāng)前目錄作為Root Document只需要這條命令即可:
php -S localhost:3300

也可以指定其它路徑
php -S localhost:3300 -t /path/to/root

還可以指定路由
php -S localhost:3300 router.php

命名空間(php5.3)
命名空間的分隔符為反斜桿
namespace fox\lanmps\Table; class Select {}

獲取完整類別名稱
PHP5.3 中引入命名空間的別名類和命名空間短版本的功能。雖然這并不適用于字符串類名稱
use Some\Deeply\Nested\Namespace\FooBar; // does not work, because this will try to use the global FooBar class $reflection = new ReflectionClass('FooBar'); echo FooBar::class;

為了解決這個(gè)問題采用新的FooBar::class語法,它返回類的完整類別名稱
命名空間 use 操作符開始支持函數(shù)和常量的導(dǎo)入
namespace Name\Space { const FOO = 42; function f() { echo FUNCTION."\n"; } } namespace { use const Name\Space\FOO; use function Name\Space\f; echo FOO."\n"; f(); }

輸出 42 Name\Space\f
Group use declarations
從同一 namespace 導(dǎo)入的類、函數(shù)和常量現(xiàn)在可以通過單個(gè) use 語句 一次性導(dǎo)入了。
//PHP7之前use some\namespace\ClassA;use some\namespace\ClassB;use some\namespace\ClassC as C;use function some\namespace\fn_a;use function some\namespace\fn_b;use function some\namespace\fn_c;use const some\namespace\ConstA;use const some\namespace\ConstB;use const some\namespace\ConstC;// PHP7之后use some\namespace{ClassA, ClassB, ClassC as C};use function some\namespace{fn_a, fn_b, fn_c};use const some\namespace{ConstA, ConstB, ConstC};

支持延遲靜態(tài)綁定
static關(guān)鍵字來引用當(dāng)前類,即實(shí)現(xiàn)了延遲靜態(tài)綁定
class A { public static function who() { echo CLASS; } public static function test() { static::who(); // 這里實(shí)現(xiàn)了延遲的靜態(tài)綁定 } } class B extends A { public static function who() { echo CLASS; } }B::test();

輸出結(jié)果: B
支持goto語句
多數(shù)計(jì)算機(jī)程序設(shè)計(jì)語言中都支持無條件轉(zhuǎn)向語句goto,當(dāng)程序執(zhí)行到goto語句時(shí),即轉(zhuǎn)向由goto語句中的標(biāo)號(hào)指出的程序位置繼續(xù)執(zhí)行。盡管goto語句有可能會(huì)導(dǎo)致程序流程不清晰,可讀性減弱,但在某些情況下具有其獨(dú)特的方便之處,例如中斷深度嵌套的循環(huán)和 if 語句。
goto a; echo 'Foo'; a: echo 'Bar'; for($i=0,$j=50; $i<100; $i++) { while($j--) { if($j==17) goto end; } } echo "i = $i"; end: echo 'j hit 17';

支持閉包、Lambda/Anonymous函數(shù)
閉包(Closure)函數(shù)和Lambda函數(shù)的概念來自于函數(shù)編程領(lǐng)域。例如JavaScript 是支持閉包和 lambda 函數(shù)的最常見語言之一。 在PHP中,我們也可以通過create_function()在代碼運(yùn)行時(shí)創(chuàng)建函數(shù)。但有一個(gè)問題:創(chuàng)建的函數(shù)僅在運(yùn)行時(shí)才被編譯,而不與其它代碼同時(shí)被編譯成執(zhí)行碼,因此我們無法使用類似APC這樣的執(zhí)行碼緩存來提高代碼執(zhí)行效率。 在PHP5.3中,我們可以使用Lambda/匿名函數(shù)來定義一些臨時(shí)使用(即用即棄型)的函數(shù),以作為array_map()/array_walk()等函數(shù)的回調(diào)函數(shù)。
echo preg_replace_callback('-([a-z])', function ($match) { return strtoupper($match[1]); }, 'hello-world'); // 輸出 helloWorld $greet = function($name) { printf("Hello %s\r\n", $name); }; $greet('World'); $greet('PHP'); //...在某個(gè)類中 $callback = function ($quantity, $product) use ($tax, &$total) { $pricePerItem = constant(CLASS . "::PRICE_" . strtoupper($product)); $total += ($pricePerItem * $quantity) * ($tax + 1.0); };

魔術(shù)方法__callStatic()和__invoke()
PHP中原本有一個(gè)魔術(shù)方法__call(),當(dāng)代碼調(diào)用對(duì)象的某個(gè)不存在的方法時(shí)該魔術(shù)方法會(huì)被自動(dòng)調(diào)用。新增的__callStatic()方法則只用于靜態(tài)類方法。當(dāng)嘗試調(diào)用類中不存在的靜態(tài)方法時(shí),__callStatic()魔術(shù)方法將被自動(dòng)調(diào)用。
class MethodTest { public function __call($name, $arguments) { // 參數(shù) $name 大小寫敏感 echo "調(diào)用對(duì)象方法 '$name' " . implode(' -- ', $arguments). "\n"; } /** PHP 5.3.0 以上版本中本類方法有效 */ public static function __callStatic($name, $arguments) { // 參數(shù) $name 大小寫敏感 echo "調(diào)用靜態(tài)方法 '$name' " . implode(' -- ', $arguments). "\n"; } } $obj = new MethodTest; $obj->runTest('通過對(duì)象調(diào)用'); MethodTest::runTest('靜態(tài)調(diào)用'); // As of PHP 5.3.0

以上代碼執(zhí)行后輸出如下: 調(diào)用對(duì)象方法’runTest’ –- 通過對(duì)象調(diào)用調(diào)用靜態(tài)方法’runTest’ –- 靜態(tài)調(diào)用 以函數(shù)形式來調(diào)用對(duì)象時(shí),__invoke()方法將被自動(dòng)調(diào)用。
class MethodTest { public function __call($name, $arguments) { // 參數(shù) $name 大小寫敏感 echo "Calling object method '$name' " . implode(', ', $arguments). "\n"; } /** PHP 5.3.0 以上版本中本類方法有效 */ public static function __callStatic($name, $arguments) { // 參數(shù) $name 大小寫敏感 echo "Calling static method '$name' " . implode(', ', $arguments). "\n"; } } $obj = new MethodTest; $obj->runTest('in object context'); MethodTest::runTest('in static context'); // As of PHP 5.3.0

Nowdoc語法
用法和Heredoc類似,但使用單引號(hào)。Heredoc則需要通過使用雙引號(hào)來聲明。 Nowdoc中不會(huì)做任何變量解析,非常適合于傳遞一段PHP代碼。
// Nowdoc 單引號(hào) PHP 5.3之后支持 $name = 'MyName'; echo <<<'EOT' My name is "$name". EOT; //上面代碼輸出 My name is "$name". ((其中變量不被解析) // Heredoc不加引號(hào) echo <<<FOOBAR Hello World! FOOBAR; //或者 雙引號(hào) PHP 5.3之后支持 echo <<<"FOOBAR" Hello World! FOOBAR;

支持通過Heredoc來初始化靜態(tài)變量、類成員和類常量。
// 靜態(tài)變量 function foo() { static $bar = <<<LABEL Nothing in here... LABEL; } // 類成員、常量 class foo { const BAR = <<<FOOBAR Constant example FOOBAR; public $baz = <<<FOOBAR Property example FOOBAR; }

在類外也可使用const來定義常量
//PHP中定義常量通常是用這種方式 define("CONSTANT", "Hello world."); //并且新增了一種常量定義方式 const CONSTANT = 'Hello World';

三元運(yùn)算符增加了一個(gè)快捷書寫方式
原本格式為是(expr1) ? (expr2) : (expr3) 如果expr1結(jié)果為True,則返回expr2的結(jié)果。 新增一種書寫方式,可以省略中間部分,書寫為expr1 ?: expr3 如果expr1結(jié)果為True,則返回expr1的結(jié)果
$expr1=1;$expr2=2;//原格式 $expr=$expr1?$expr1:$expr2 //新格式 $expr=$expr1?:$expr2

輸出結(jié)果: 1 1
空合并運(yùn)算符(??)
簡(jiǎn)化判斷
$param = $_GET['param'] ?? 1;

相當(dāng)于:
$param = isset($_GET['param']) ? $_GET['param'] : 1;

Json更懂中文(JSON_UNESCAPED_UNICODE)
echo json_encode("中文", JSON_UNESCAPED_UNICODE); //輸出:"中文"

二進(jìn)制
$bin = 0b1101; echo $bin; //13

Unicode codepoint 轉(zhuǎn)譯語法
這接受一個(gè)以16進(jìn)制形式的 Unicode codepoint,并打印出一個(gè)雙引號(hào)或heredoc包圍的 UTF-8 編碼格式的字符串。 可以接受任何有效的 codepoint,并且開頭的 0 是可以省略的。
echo "\u{9876}"

舊版輸出:\u{9876} 新版輸入:頂
使用 ** 進(jìn)行冪運(yùn)算
加入右連接運(yùn)算符 ** 來進(jìn)行冪運(yùn)算。 同時(shí)還支持簡(jiǎn)寫的 **= 運(yùn)算符,表示進(jìn)行冪運(yùn)算并賦值。
printf("2 ** 3 == %d\n", 2 ** 3);printf("2 ** 3 ** 2 == %d\n", 2 ** 3 ** 2);$a = 2;$a **= 3;printf("a == %d\n", $a);

輸出 2 ** 3 == 8 2 ** 3 ** 2 == 512 a == 8
太空船操作符(組合比較符)
太空船操作符用于比較兩個(gè)表達(dá)式。當(dāng) a大于、等于或小于b 時(shí)它分別返回 -1 、 0 或 1 。 比較的原則是沿用 PHP 的常規(guī)比較規(guī)則進(jìn)行的。
// Integersecho 1 <=> 1; // 0echo 1 <=> 2; // -1echo 2 <=> 1; // 1// Floatsecho 1.5 <=> 1.5; // 0echo 1.5 <=> 2.5; // -1echo 2.5 <=> 1.5; // 1// Stringsecho "a" <=> "a"; // 0echo "a" <=> "b"; // -1echo "b" <=> "a"; // 1

Traits
Traits提供了一種靈活的代碼重用機(jī)制,即不像interface一樣只能定義方法但不能實(shí)現(xiàn),又不能像class一樣只能單繼承。至于在實(shí)踐中怎樣使用,還需要深入思考。 魔術(shù)常量為TRAIT
官網(wǎng)的一個(gè)例子: 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 */

array 數(shù)組簡(jiǎn)寫語法
$arr = [1,'james', 'james@fwso.cn']; $array = [   "foo" => "bar",   "bar" => "foo"   ];

array 數(shù)組中某個(gè)索引值簡(jiǎn)寫
function myfunc() { return array(1,'james', 'james@fwso.cn'); }echo myfunc()[1]; $name = explode(",", "Laruence,male")[0]; explode(",", "Laruence,male")[3] = "phper";

非變量array和string也能支持下標(biāo)獲取了
echo array(1, 2, 3)[0]; echo [1, 2, 3][0]; echo "foobar"[2];

支持為負(fù)的字符串偏移量
現(xiàn)在所有接偏移量的內(nèi)置的基于字符串的函數(shù)都支持接受負(fù)數(shù)作為偏移量,包括數(shù)組解引用操作符([]).
var_dump("abcdef"[-2]);var_dump(strpos("aabbcc", "b", -3));

以上例程會(huì)輸出:
string (1) "e"int(3)

常量引用
“常量引用”意味著數(shù)組可以直接操作字符串和數(shù)組字面值。舉兩個(gè)例子:
function randomHexString($length) { $str = ''; for ($i = 0; $i < $length; ++$i) { $str .= "0123456789abcdef"[mt_rand(0, 15)]; // direct dereference of string } } function randomBool() { return [false, true][mt_rand(0, 1)]; // direct dereference of array }

常量增強(qiáng)
允許常量計(jì)算,允許使用包含數(shù)字、字符串字面值和常量的標(biāo)量表達(dá)式
const A = 2; const B = A + 1; class C { const STR = "hello"; const STR2 = self::STR + ", world"; }

允許常量作為函數(shù)參數(shù)默認(rèn)
function test($arg = C::STR2)

類常量可見性 現(xiàn)在起支持設(shè)置類常量的可見性。
class ConstDemo{ const PUBLIC_CONST_A = 1; public const PUBLIC_CONST_B = 2; protected const PROTECTED_CONST = 3; private const PRIVATE_CONST = 4;}

通過define()定義常量數(shù)組
define('ANIMALS', ['dog', 'cat', 'bird']);echo ANIMALS[1]; // outputs "cat"

函數(shù)變量類型聲明
兩種模式 : 強(qiáng)制 ( 默認(rèn) ) 和 嚴(yán)格模式 類型:array,object(對(duì)象),string、int、float和 bool
class bar { function foo(bar $foo) { } //其中函數(shù)foo中的參數(shù)規(guī)定了傳入的參數(shù)必須為bar類的實(shí)例,否則系統(tǒng)會(huì)判斷出錯(cuò)。同樣對(duì)于數(shù)組來說,也可以進(jìn)行判斷,比如: function foo(array $foo) { } }   foo(array(1, 2, 3)); // 正確,因?yàn)閭魅氲氖菙?shù)組   foo(123); // 不正確,傳入的不是數(shù)組function add(int $a) { return 1+$a; } var_dump(add(2));function foo(int $i) { ... } foo(1); // $i = 1 foo(1.0); // $i = 1 foo("1"); // $i = 1 foo("1abc"); // not yet clear, maybe $i = 1 with notice foo(1.5); // not yet clear, maybe $i = 1 with notice foo([]); // error foo("abc"); // error

參數(shù)跳躍
如果你有一個(gè)函數(shù)接受多個(gè)可選的參數(shù),目前沒有辦法只改變最后一個(gè)參數(shù),而讓其他所有參數(shù)為默認(rèn)值。 RFC上的例子,如果你有一個(gè)函數(shù)如下:
function create_query($where, $order_by, $join_type='', $execute = false, $report_errors = true) { ... }

那么有沒有辦法設(shè)置$report_errors=false,而其他兩個(gè)為默認(rèn)值。為了解決這個(gè)跳躍參數(shù)的問題而提出:
create_query("deleted=0", "name", default, default, false);

可變函數(shù)參數(shù)
代替 func_get_args()
function add(...$args) { $result = 0; foreach($args as $arg) $result += $arg; return $result; }

可為空(Nullable)類型
類型現(xiàn)在允許為空,當(dāng)啟用這個(gè)特性時(shí),傳入的參數(shù)或者函數(shù)返回的結(jié)果要么是給定的類型,要么是 null 。可以通過在類型前面加上一個(gè)問號(hào)來使之成為可為空的。
function test(?string $name){ var_dump($name);}

以上例程會(huì)輸出:
string(5) "tpunt"NULLUncaught Error: Too few arguments to function test(), 0 passed in...

Void 函數(shù)
在PHP 7 中引入的其他返回值類型的基礎(chǔ)上,一個(gè)新的返回值類型void被引入。 返回值聲明為 void 類型的方法要么干脆省去 return 語句,要么使用一個(gè)空的 return 語句。 對(duì)于 void 函數(shù)來說,null 不是一個(gè)合法的返回值。
function swap(&$left, &$right) : void{ if ($left === $right) { return; } $tmp = $left; $left = $right; $right = $tmp;}$a = 1;$b = 2;var_dump(swap($a, $b), $a, $b);

以上例程會(huì)輸出:
nullint(2)int(1)

試圖去獲取一個(gè) void 方法的返回值會(huì)得到 null ,并且不會(huì)產(chǎn)生任何警告。這么做的原因是不想影響更高層次的方法。
返回值類型聲明
函數(shù)和匿名函數(shù)都可以指定返回值的類型
function show(): array { return [1,2,3,4]; }function arraysSum(array ...$arrays): array{return array_map(function(array $array): int {return array_sum($array);}, $arrays);}

參數(shù)解包功能
在調(diào)用函數(shù)的時(shí)候,通過 … 操作符可以把數(shù)組或者可遍歷對(duì)象解包到參數(shù)列表,這和Ruby等語言中的擴(kuò)張(splat)操作符類似
function add($a, $b, $c) { return $a + $b + $c; } $arr = [2, 3]; add(1, ...$arr);

實(shí)例化類
class test{ function show(){ return 'test'; } } echo (new test())->show();

支持 Class::{expr}() 語法
foreach ([new Human("Gonzalo"), new Human("Peter")] as $human) { echo $human->{'hello'}(); }

Callable typehint
function foo(callable $callback) { }


foo("false"); //錯(cuò)誤,因?yàn)閒alse不是callable類型   foo("printf"); //正確   foo(function(){}); //正確 class A {   static function show() { } }   foo(array("A", "show")); //正確

Getter 和 Setter
如果你從不喜歡寫這些getXYZ()和setXYZ($value)方法,那么這應(yīng)該是你最受歡迎的改變。提議添加一個(gè)新的語法來定義一個(gè)屬性的設(shè)置/讀取:
class TimePeriod { public $seconds; public $hours { get { return $this->seconds / 3600; } set { $this->seconds = $value * 3600; } } } $timePeriod = new TimePeriod; $timePeriod->hours = 10; var_dump($timePeriod->seconds); // int(36000) var_dump($timePeriod->hours); // int(10)

迭代器 yield
目前,自定義迭代器很少使用,因?yàn)樗鼈兊膶?shí)現(xiàn),需要大量的樣板代碼。生成器解決這個(gè)問題,并提供了一種簡(jiǎn)單的樣板代碼來創(chuàng)建迭代器。 例如,你可以定義一個(gè)范圍函數(shù)作為迭代器:
function *xrange($start, $end, $step = 1) { for ($i = $start; $i < $end; $i += $step) { yield $i; } } foreach (xrange(10, 20) as $i) { // ... }

上述xrange函數(shù)具有與內(nèi)建函數(shù)相同的行為,但有一點(diǎn)區(qū)別:不是返回一個(gè)數(shù)組的所有值,而是返回一個(gè)迭代器動(dòng)態(tài)生成的值。
列表解析和生成器表達(dá)式
列表解析提供一個(gè)簡(jiǎn)單的方法對(duì)數(shù)組進(jìn)行小規(guī)模操作:
$firstNames = [foreach ($users as $user) yield $user->firstName];

上述列表解析相等于下面的代碼:
$firstNames = []; foreach ($users as $user) { $firstNames[] = $user->firstName; }

也可以這樣過濾數(shù)組:
$underageUsers = [foreach ($users as $user) if ($user->age < 18) yield $user];

生成器表達(dá)式也很類似,但是返回一個(gè)迭代器(用于動(dòng)態(tài)生成值)而不是一個(gè)數(shù)組。
生成器的返回值
在PHP5.5引入生成器的概念。生成器函數(shù)每執(zhí)行一次就得到一個(gè)yield標(biāo)識(shí)的值。在PHP7中,當(dāng)生成器迭代完成后,可以獲取該生成器函數(shù)的返回值。通過Generator::getReturn()得到。
function generator(){ yield 1; yield 2; yield 3; return "a";}$generatorClass = ("generator")();foreach ($generatorClass as $val) { echo $val ." ";}echo $generatorClass->getReturn();

輸出為:1 2 3 a
生成器中引入其他生成器
在生成器中可以引入另一個(gè)或幾個(gè)生成器,只需要寫yield from functionName1
function generator1(){ yield 1; yield 2; yield from generator2(); yield from generator3();}function generator2(){ yield 3; yield 4;}function generator3(){ yield 5; yield 6;}foreach (generator1() as $val) { echo $val, " ";}

輸出:1 2 3 4 5 6
finally關(guān)鍵字
這個(gè)和Java中的finally一樣,經(jīng)典的try … catch … finally 三段式異常處理。
多異常捕獲處理
一個(gè)catch語句塊現(xiàn)在可以通過管道字符(|)來實(shí)現(xiàn)多個(gè)異常的捕獲。 這對(duì)于需要同時(shí)處理來自不同類的不同異常時(shí)很有用。
try { // some code} catch (FirstException | SecondException $e) { // handle first and second exceptions} catch (\Exception $e) { // ...} finally{//}

foreach 支持list()
對(duì)于“數(shù)組的數(shù)組”進(jìn)行迭代,之前需要使用兩個(gè)foreach,現(xiàn)在只需要使用foreach + list了,但是這個(gè)數(shù)組的數(shù)組中的每個(gè)數(shù)組的個(gè)數(shù)需要一樣。看文檔的例子一看就明白了。
$array = [ [1, 2], [3, 4], ]; foreach ($array as list($a, $b)) { echo "A: $a; B: $b\n"; }

短數(shù)組語法 Symmetric array destructuring
短數(shù)組語法([])現(xiàn)在可以用于將數(shù)組的值賦給一些變量(包括在foreach中)。 這種方式使從數(shù)組中提取值變得更為容易。
$data = [ ['id' => 1, 'name' => 'Tom'], ['id' => 2, 'name' => 'Fred'],];while (['id' => $id, 'name' => $name] = $data) { // logic here with $id and $name}

list()現(xiàn)在支持鍵名
現(xiàn)在list()支持在它內(nèi)部去指定鍵名。這意味著它可以將任意類型的數(shù)組 都賦值給一些變量(與短數(shù)組語法類似)
$data = [ ['id' => 1, 'name' => 'Tom'], ['id' => 2, 'name' => 'Fred'],];while (list('id' => $id, 'name' => $name) = $data) { // logic here with $id and $name}

iterable 偽類
現(xiàn)在引入了一個(gè)新的被稱為iterable的偽類 (與callable類似)。 這可以被用在參數(shù)或者返回值類型中,它代表接受數(shù)組或者實(shí)現(xiàn)了Traversable接口的對(duì)象。 至于子類,當(dāng)用作參數(shù)時(shí),子類可以收緊父類的iterable類型到array 或一個(gè)實(shí)現(xiàn)了Traversable的對(duì)象。對(duì)于返回值,子類可以拓寬父類的 array或?qū)ο蠓祷刂殿愋偷絠terable。
function iterator(iterable $iter){ foreach ($iter as $val) { // }}

ext/openssl 支持 AEAD
通過給openssl_encrypt()和openssl_decrypt() 添加額外參數(shù),現(xiàn)在支持了AEAD (模式 GCM and CCM)。 通過 Closure::fromCallable() 將callables轉(zhuǎn)為閉包 Closure新增了一個(gè)靜態(tài)方法,用于將callable快速地 轉(zhuǎn)為一個(gè)Closure 對(duì)象。
class Test{ public function exposeFunction() { return Closure::fromCallable([$this, 'privateFunction']); } private function privateFunction($param) { var_dump($param); }}$privFunc = (new Test)->exposeFunction();$privFunc('some value');

以上例程會(huì)輸出:
string(10) "some value"

匿名類
現(xiàn)在支持通過 new class 來實(shí)例化一個(gè)匿名類,這可以用來替代一些“用后即焚”的完整類定義。
interface Logger{ public function log(string $msg);}class Application{ private $logger; public function getLogger(): Logger { return $this->logger; } public function setLogger(Logger $logger) { $this->logger = $logger; }}$app = new Application;$app->setLogger(new class implements Logger{ public function log(string $msg) { echo $msg; }});var_dump($app->getLogger());

Closure::call()
Closure::call() 現(xiàn)在有著更好的性能,簡(jiǎn)短干練的暫時(shí)綁定一個(gè)方法到對(duì)象上閉包并調(diào)用它。
class Test{ public $name = "lixuan";}//PHP7和PHP5.6都可以$getNameFunc = function () { return $this->name;};$name = $getNameFunc->bindTo(new Test, 'Test');echo $name();//PHP7可以,PHP5.6報(bào)錯(cuò)$getX = function () { return $this->name;};echo $getX->call(new Test);

為unserialize()提供過濾
這個(gè)特性旨在提供更安全的方式解包不可靠的數(shù)據(jù)。它通過白名單的方式來防止?jié)撛诘拇a注入。
//將所有對(duì)象分為__PHP_Incomplete_Class對(duì)象$data = unserialize($foo, ["allowed_classes" => false]);//將所有對(duì)象分為__PHP_Incomplete_Class 對(duì)象 除了ClassName1和ClassName2$data = unserialize($foo, ["allowed_classes" => ["ClassName1", "ClassName2"]);//默認(rèn)行為,和 unserialize($foo)相同$data = unserialize($foo, ["allowed_classes" => true]);

IntlChar
新增加的 IntlChar 類旨在暴露出更多的 ICU 功能。這個(gè)類自身定義了許多靜態(tài)方法用于操作多字符集的 unicode 字符。Intl是Pecl擴(kuò)展,使用前需要編譯進(jìn)PHP中,也可apt-get/yum/port install php5-intl
printf('%x', IntlChar::CODEPOINT_MAX);echo IntlChar::charName('@');var_dump(IntlChar::ispunct('!'));

以上例程會(huì)輸出: 10ffff COMMERCIAL AT bool(true)
預(yù)期
預(yù)期是向后兼用并增強(qiáng)之前的 assert() 的方法。 它使得在生產(chǎn)環(huán)境中啟用斷言為零成本,并且提供當(dāng)斷言失敗時(shí)拋出特定異常的能力。 老版本的API出于兼容目的將繼續(xù)被維護(hù),assert()現(xiàn)在是一個(gè)語言結(jié)構(gòu),它允許第一個(gè)參數(shù)是一個(gè)表達(dá)式,而不僅僅是一個(gè)待計(jì)算的 string或一個(gè)待測(cè)試的boolean。
ini_set('assert.exception', 1);class CustomError extends AssertionError {}assert(false, new CustomError('Some error message'));

以上例程會(huì)輸出: Fatal error: Uncaught CustomError: Some error message
intdiv()
接收兩個(gè)參數(shù)作為被除數(shù)和除數(shù),返回他們相除結(jié)果的整數(shù)部分。
var_dump(intdiv(7, 2));

輸出int(3)
CSPRNG
新增兩個(gè)函數(shù): random_bytes() and random_int().可以加密的生產(chǎn)被保護(hù)的整數(shù)和字符串。總之隨機(jī)數(shù)變得安全了。 random_bytes — 加密生存被保護(hù)的偽隨機(jī)字符串 random_int —加密生存被保護(hù)的偽隨機(jī)整數(shù)
preg_replace_callback_array()
新增了一個(gè)函數(shù)preg_replace_callback_array(),使用該函數(shù)可以使得在使用preg_replace_callback()函數(shù)時(shí)代碼變得更加優(yōu)雅。在PHP7之前,回調(diào)函數(shù)會(huì)調(diào)用每一個(gè)正則表達(dá)式,回調(diào)函數(shù)在部分分支上是被污染了。
Session options
現(xiàn)在,session_start()函數(shù)可以接收一個(gè)數(shù)組作為參數(shù),可以覆蓋php.ini中session的配置項(xiàng)。 比如,把cache_limiter設(shè)置為私有的,同時(shí)在閱讀完session后立即關(guān)閉。
session_start(['cache_limiter' => 'private', 'read_and_close' => true,]);

$_SERVER[“REQUEST_TIME_FLOAT”]
這個(gè)是用來統(tǒng)計(jì)服務(wù)請(qǐng)求時(shí)間的,并用ms(毫秒)來表示
echo "腳本執(zhí)行時(shí)間 ", round(microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"], 2), "s";

empty() 支持任意表達(dá)式
empty() 現(xiàn)在支持傳入一個(gè)任意表達(dá)式,而不僅是一個(gè)變量
function always_false() { return false;}if (empty(always_false())) { echo 'This will be printed.';}if (empty(true)) { echo 'This will not be printed.';}

輸出 This will be printed.
php://input 可以被復(fù)用
php://input 開始支持多次打開和讀取,這給處理POST數(shù)據(jù)的模塊的內(nèi)存占用帶來了極大的改善。
Upload progress 文件上傳
Session提供了上傳進(jìn)度支持,通過$_SESSION[“upload_progress_name”]就可以獲得當(dāng)前文件上傳的進(jìn)度信息,結(jié)合Ajax就能很容易實(shí)現(xiàn)上傳進(jìn)度條了。 詳細(xì)的看http://www.laruence.com/2011/10/10/2217.html
大文件上傳支持
可以上傳超過2G的大文件。
GMP支持操作符重載
GMP 對(duì)象支持操作符重載和轉(zhuǎn)換為標(biāo)量,改善了代碼的可讀性,如:
$a = gmp_init(42); $b = gmp_init(17); // Pre-5.6 code: var_dump(gmp_add($a, $b)); var_dump(gmp_add($a, 17)); var_dump(gmp_add(42, $b)); // New code: var_dump($a + $b); var_dump($a + 17); var_dump(42 + $b);

JSON 序列化對(duì)象
實(shí)現(xiàn)了JsonSerializable接口的類的實(shí)例在json_encode序列化的之前會(huì)調(diào)用jsonSerialize方法,而不是直接序列化對(duì)象的屬性。 參考http://www.laruence.com/2011/10/10/2204.html
HTTP狀態(tài)碼在200-399范圍內(nèi)均被認(rèn)為訪問成功
支持動(dòng)態(tài)調(diào)用靜態(tài)方法
class Test{ public static function testgo() { echo "gogo!"; } } $class = 'Test'; $action = 'testgo'; $class::$action(); //輸出 "gogo!"

棄用e修飾符
e修飾符是指示preg_replace函數(shù)用來評(píng)估替換字符串作為PHP代碼,而不只是僅僅做一個(gè)簡(jiǎn)單的字符串替換。不出所料,這種行為會(huì)源源不斷的出現(xiàn)安全問題。這就是為什么在PHP5.5 中使用這個(gè)修飾符將拋出一個(gè)棄用警告。作為替代,你應(yīng)該使用preg_replace_callback函數(shù)。你可以從RFC找到更多關(guān)于這個(gè)變化相應(yīng)的信息。
新增函數(shù) boolval
PHP已經(jīng)實(shí)現(xiàn)了strval、intval和floatval的函數(shù)。為了達(dá)到一致性將添加boolval函數(shù)。它完全可以作為一個(gè)布爾值計(jì)算,也可以作為一個(gè)回調(diào)函數(shù)。
新增函數(shù)hash_pbkdf2
PBKDF2全稱“Password-Based Key Derivation Function 2”,正如它的名字一樣,是一種從密碼派生出加密密鑰的算法。這就需要加密算法,也可以用于對(duì)密碼哈希。更廣泛的說明和用法示例
array_column
//從數(shù)據(jù)庫獲取一列,但返回是數(shù)組。 $userNames = []; foreach ($users as $user) { $userNames[] = $user['name']; } //以前獲取數(shù)組某列值,現(xiàn)在如下 $userNames = array_column($users, 'name');

一個(gè)簡(jiǎn)單的密碼散列API
$password = "foo"; // creating the hash $hash = password_hash($password, PASSWORD_BCRYPT); // verifying a password if (password_verify($password, $hash)) { // password correct! } else { // password wrong! }

異步信號(hào)處理 Asynchronous signal handling
A new function called pcntl_async_signals() has been introduced to enable asynchronous signal handling without using ticks (which introduce a lot of overhead). 增加了一個(gè)新函數(shù) pcntl_async_signals()來處理異步信號(hào),不需要再使用ticks(它會(huì)增加占用資源)
pcntl_async_signals(true); // turn on async signalspcntl_signal(SIGHUP, function($sig) { echo "SIGHUP\n";});posix_kill(posix_getpid(), SIGHUP);

以上例程會(huì)輸出:
SIGHUP

HTTP/2 服務(wù)器推送支持 ext/curl
Support for server push has been added to the CURL extension (requires version 7.46 and above). This can be leveraged through the curl_multi_setopt() function with the new CURLMOPT_PUSHFUNCTION constant. The constants CURL_PUST_OK and CURL_PUSH_DENY have also been added so that the execution of the server push callback can either be approved or denied. 蹩腳英語: 對(duì)于服務(wù)器推送支持添加到curl擴(kuò)展(需要7.46及以上版本)。 可以通過用新的CURLMOPT_PUSHFUNCTION常量 讓curl_multi_setopt()函數(shù)使用。 也增加了常量CURL_PUST_OK和CURL_PUSH_DENY,可以批準(zhǔn)或拒絕 服務(wù)器推送回調(diào)的執(zhí)行
php.ini中可使用變量
PHP default_charset 默認(rèn)字符集 為UTF-8
ext/phar、ext/intl、ext/fileinfo、ext/sqlite3和ext/enchant等擴(kuò)展默認(rèn)隨PHP綁定發(fā)布。其中Phar可用于打包PHP程序,類似于Java中的jar機(jī)制
PHP7.1不兼容性
1.當(dāng)傳遞參數(shù)過少時(shí)將拋出錯(cuò)誤
在過去如果我們調(diào)用一個(gè)用戶定義的函數(shù)時(shí),提供的參數(shù)不足,那么將會(huì)產(chǎn)生一個(gè)警告(warning)。 現(xiàn)在,這個(gè)警告被提升為一個(gè)錯(cuò)誤異常(Error exception)。這個(gè)變更僅對(duì)用戶定義的函數(shù)生效, 并不包含內(nèi)置函數(shù)。例如:
function test($param){}test();

輸出:
Uncaught Error: Too few arguments to function test(), 0 passed in %s on line %d and exactly 1 expected in %s:%d

2.禁止動(dòng)態(tài)調(diào)用函數(shù)
禁止動(dòng)態(tài)調(diào)用函數(shù)如下 assert() - with a string as the first argument compact() extract() func_get_args() func_get_arg() func_num_args() get_defined_vars() mb_parse_str() - with one arg parse_str() - with one arg
(function () { 'func_num_args'();})();

輸出
Warning: Cannot call func_num_args() dynamically in %s on line %d

3.無效的類,接口,trait名稱命名
以下名稱不能用于 類,接口或trait 名稱命名: void iterable
4.Numerical string conversions now respect scientific notation
Integer operations and conversions on numerical strings now respect scientific notation. This also includes the (int) cast operation, and the following functions: intval() (where the base is 10), settype(), decbin(), decoct(), and dechex().
5.mt_rand 算法修復(fù)
mt_rand() will now default to using the fixed version of the Mersenne Twister algorithm. If deterministic output from mt_srand() was relied upon, then the MT_RAND_PHP with the ability to preserve the old (incorrect) implementation via an additional optional second parameter to mt_srand().
6.rand() 別名 mt_rand() 和 srand() 別名 mt_srand()
rand() and srand() have now been made aliases to mt_rand() and mt_srand(), respectively. This means that the output for the following functions have changes: rand(), shuffle(), str_shuffle(), and array_rand().
7.Disallow the ASCII delete control character in identifiers
The ASCII delete control character (0x7F) can no longer be used in identifiers that are not quoted.
8.error_log changes with syslog value
If the error_log ini setting is set to syslog, the PHP error levels are mapped to the syslog error levels. This brings finer differentiation in the error logs in contrary to the previous approach where all the errors are logged with the notice level only.
9.在不完整的對(duì)象上不再調(diào)用析構(gòu)方法
析構(gòu)方法在一個(gè)不完整的對(duì)象(例如在構(gòu)造方法中拋出一個(gè)異常)上將不再會(huì)被調(diào)用
10.call_user_func()不再支持對(duì)傳址的函數(shù)的調(diào)用
call_user_func() 現(xiàn)在在調(diào)用一個(gè)以引用作為參數(shù)的函數(shù)時(shí)將始終失敗。
11.字符串不再支持空索引操作符 The empty index operator is not supported for strings anymore
對(duì)字符串使用一個(gè)空索引操作符(例如str[]=x)將會(huì)拋出一個(gè)致命錯(cuò)誤, 而不是靜默地將其轉(zhuǎn)為一個(gè)數(shù)組
12.ini配置項(xiàng)移除
下列ini配置項(xiàng)已經(jīng)被移除: session.entropy_file session.entropy_length session.hash_function session.hash_bits_per_character
PHP7.0 不兼容性
1、foreach不再改變內(nèi)部數(shù)組指針
在PHP7之前,當(dāng)數(shù)組通過 foreach 迭代時(shí),數(shù)組指針會(huì)移動(dòng)。現(xiàn)在開始,不再如此,見下面代碼。
$array = [0, 1, 2];foreach ($array as &$val) { var_dump(current($array));}

PHP5輸出: int(1) int(2) bool(false) PHP7輸出: int(0) int(0) int(0)
2、foreach通過引用遍歷時(shí),有更好的迭代特性
當(dāng)使用引用遍歷數(shù)組時(shí),現(xiàn)在 foreach 在迭代中能更好的跟蹤變化。例如,在迭代中添加一個(gè)迭代值到數(shù)組中,參考下面的代碼:
$array = [0];foreach ($array as &$val) { var_dump($val); $array[1] = 1;}

PHP5輸出: int(0) PHP7輸出: int(0) int(1)
3、十六進(jìn)制字符串不再被認(rèn)為是數(shù)字
含十六進(jìn)制字符串不再被認(rèn)為是數(shù)字
var_dump("0x123" == "291");var_dump(is_numeric("0x123"));var_dump("0xe" + "0x1");var_dump(substr("foo", "0x1"));

PHP5輸出: bool(true) bool(true) int(15) string(2) “oo” PHP7輸出: bool(false) bool(false) int(0) Notice: A non well formed numeric value encountered in /tmp/test.php on line 5 string(3) “foo”
4、PHP7中被移除的函數(shù)
被移除的函數(shù)列表如下: call_user_func() 和 call_user_func_array()從PHP 4.1.0開始被廢棄。 已廢棄的 mcrypt_generic_end() 函數(shù)已被移除,請(qǐng)使用mcrypt_generic_deinit()代替。 已廢棄的 mcrypt_ecb(), mcrypt_cbc(), mcrypt_cfb() 和 mcrypt_ofb() 函數(shù)已被移除。 set_magic_quotes_runtime(), 和它的別名 magic_quotes_runtime()已被移除. 它們?cè)赑HP 5.3.0中已經(jīng)被廢棄,并且 在in PHP 5.4.0也由于魔術(shù)引號(hào)的廢棄而失去功能。 已廢棄的 set_socket_blocking() 函數(shù)已被移除,請(qǐng)使用stream_set_blocking()代替。 dl()在 PHP-FPM 不再可用,在 CLI 和 embed SAPIs 中仍可用。 GD庫中下列函數(shù)被移除:imagepsbbox()、imagepsencodefont()、imagepsextendfont()、imagepsfreefont()、imagepsloadfont()、imagepsslantfont()、imagepstext() 在配置文件php.ini中,always_populate_raw_post_data、asp_tags、xsl.security_prefs被移除了。
5、new 操作符創(chuàng)建的對(duì)象不能以引用方式賦值給變量
new 操作符創(chuàng)建的對(duì)象不能以引用方式賦值給變量
class C {}$c =& new C;

PHP5輸出: Deprecated: Assigning the return value of new by reference is deprecated in /tmp/test.php on line 3 PHP7輸出: Parse error: syntax error, unexpected ‘new’ (T_NEW) in /tmp/test.php on line 3
6、移除了 ASP 和 script PHP 標(biāo)簽
使用類似 ASP 的標(biāo)簽,以及 script 標(biāo)簽來區(qū)分 PHP 代碼的方式被移除。 受到影響的標(biāo)簽有:<% %>、<%= %>、
7、從不匹配的上下文發(fā)起調(diào)用
在不匹配的上下文中以靜態(tài)方式調(diào)用非靜態(tài)方法, 在 PHP 5.6 中已經(jīng)廢棄, 但是在 PHP 7.0 中, 會(huì)導(dǎo)致被調(diào)用方法中未定義 $this 變量,以及此行為已經(jīng)廢棄的警告。
class A { public function test() { var_dump($this); }}// 注意:并沒有從類 A 繼承class B { public function callNonStaticMethodOfA() { A::test(); }}(new B)->callNonStaticMethodOfA();

PHP5輸出: Deprecated: Non-static method A::test() should not be called statically, assuming $this from incompatible context in /tmp/test.php on line 8 object(B)#1 (0) { } PHP7輸出: Deprecated: Non-static method A::test() should not be called statically in /tmp/test.php on line 8 Notice: Undefined variable: this in /tmp/test.php on line 3 NULL
8、在數(shù)值溢出的時(shí)候,內(nèi)部函數(shù)將會(huì)失敗
將浮點(diǎn)數(shù)轉(zhuǎn)換為整數(shù)的時(shí)候,如果浮點(diǎn)數(shù)值太大,導(dǎo)致無法以整數(shù)表達(dá)的情況下, 在之前的版本中,內(nèi)部函數(shù)會(huì)直接將整數(shù)截?cái)啵⒉粫?huì)引發(fā)錯(cuò)誤。 在 PHP 7.0 中,如果發(fā)生這種情況,會(huì)引發(fā) E_WARNING 錯(cuò)誤,并且返回 NULL。
9、JSON 擴(kuò)展已經(jīng)被 JSOND 取代
JSON 擴(kuò)展已經(jīng)被 JSOND 擴(kuò)展取代。 對(duì)于數(shù)值的處理,有以下兩點(diǎn)需要注意的: 第一,數(shù)值不能以點(diǎn)號(hào)(.)結(jié)束 (例如,數(shù)值 34. 必須寫作 34.0 或 34)。 第二,如果使用科學(xué)計(jì)數(shù)法表示數(shù)值,e 前面必須不是點(diǎn)號(hào)(.) (例如,3.e3 必須寫作 3.0e3 或 3e3)。
10、INI 文件中 # 注釋格式被移除
在配置文件INI文件中,不再支持以 # 開始的注釋行, 請(qǐng)使用 ;(分號(hào))來表示注釋。 此變更適用于 php.ini 以及用 parse_ini_file() 和 parse_ini_string() 函數(shù)來處理的文件。
11、$HTTP_RAW_POST_DATA 被移除
不再提供 $HTTP_RAW_POST_DATA 變量。 請(qǐng)使用 php://input 作為替代。
12、yield 變更為右聯(lián)接運(yùn)算符
在使用 yield 關(guān)鍵字的時(shí)候,不再需要括號(hào), 并且它變更為右聯(lián)接操作符,其運(yùn)算符優(yōu)先級(jí)介于 print 和 => 之間。 這可能導(dǎo)致現(xiàn)有代碼的行為發(fā)生改變。可以通過使用括號(hào)來消除歧義。
echo yield -1;// 在之前版本中會(huì)被解釋為:echo (yield) - 1;// 現(xiàn)在,它將被解釋為:echo yield (-1);yield $foo or die;// 在之前版本中會(huì)被解釋為:yield ($foo or die);// 現(xiàn)在,它將被解釋為:(yield $foo) or die;

PHP 7.1.x 中廢棄的特性
1.ext/mcrypt
mcrypt 擴(kuò)展已經(jīng)過時(shí)了大約10年,并且用起來很復(fù)雜。因此它被廢棄并且被 OpenSSL 所取代。 從PHP 7.2起它將被從核心代碼中移除并且移到PECL中。
2.mb_ereg_replace()和mb_eregi_replace()的Eval選項(xiàng)
對(duì)于mb_ereg_replace()和mb_eregi_replace()的 e模式修飾符現(xiàn)在已被廢棄
棄用或廢除
下面是被棄用或廢除的 INI 指令列表. 使用下面任何指令都將導(dǎo)致 錯(cuò)誤. define_syslog_variables register_globals register_long_arrays safe_mode magic_quotes_gpc magic_quotes_runtime magic_quotes_sybase 棄用 INI 文件中以 ‘#’ 開頭的注釋. 棄用函數(shù): call_user_method() (使用 call_user_func() 替代) call_user_method_array() (使用 call_user_func_array() 替代) define_syslog_variables() dl() ereg() (使用 preg_match() 替代) ereg_replace() (使用 preg_replace() 替代) eregi() (使用 preg_match() 配合 ‘i’ 修正符替代) eregi_replace() (使用 preg_replace() 配合 ‘i’ 修正符替代) set_magic_quotes_runtime() 以及它的別名函數(shù) magic_quotes_runtime() session_register() (使用 SESSION超全部變量替代)sessionunregister()(使用_SESSION 超全部變量替代) session_is_registered() (使用 $SESSION 超全部變量替代) set_socket_blocking() (使用 stream_set_blocking() 替代) split() (使用 preg_split() 替代) spliti() (使用 preg_split() 配合 ‘i’ 修正符替代) sql_regcase() mysql_db_query() (使用 mysql_select_db() 和 mysql_query() 替代) mysql_escape_string() (使用 mysql_real_escape_string() 替代) 廢棄以字符串傳遞區(qū)域設(shè)置名稱. 使用 LC* 系列常量替代. mktime() 的 is_dst 參數(shù). 使用新的時(shí)區(qū)處理函數(shù)替代. 棄用的功能: 棄用通過引用分配 new 的返回值. 調(diào)用時(shí)傳遞引用被棄用. 已棄用的多個(gè)特性 allow_call_time_pass_reference、define_syslog_variables、highlight.bg、register_globals、register_long_arrays、magic_quotes、safe_mode、zend.ze1_compatibility_mode、session.bug_compat42、session.bug_compat_warn 以及 y2k_compliance。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容