php7.0 和 php7.1新特性

PHP7.1

新特性

1.可爲空(Nullable)類型

類型如今容許爲空,當啓用這個特性時,傳入的參數或者函數返回的結果要麼是給定的類型,要麼是 null 。能夠經過在類型前面加上一個問號來使之成爲可爲空的。php

function test(?string $name) { var_dump($name); }

以上例程會輸出:css

string(5) "tpunt" NULL Uncaught Error: Too few arguments to function test(), 0 passed in...

2.Void 函數

PHP 7 中引入的其餘返回值類型的基礎上,一個新的返回值類型void被引入。 返回值聲明爲 void 類型的方法要麼乾脆省去 return 語句,要麼使用一個空的 return 語句。 對於 void 函數來講,null 不是一個合法的返回值。正則表達式

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);

以上例程會輸出:算法

null int(2) int(1)

試圖去獲取一個 void 方法的返回值會獲得 null ,而且不會產生任何警告。這麼作的緣由是不想影響更高層次的方法。sql

3.短數組語法 Symmetric array destructuring

短數組語法([])如今能夠用於將數組的值賦給一些變量(包括在foreach中)。 這種方式使從數組中提取值變得更爲容易。json

$data = [ ['id' => 1, 'name' => 'Tom'], ['id' => 2, 'name' => 'Fred'], ]; while (['id' => $id, 'name' => $name] = $data) { // logic here with $id and $name }

 

4.類常量可見性

如今起支持設置類常量的可見性。數組

class ConstDemo
{
    const PUBLIC_CONST_A = 1; public const PUBLIC_CONST_B = 2; protected const PROTECTED_CONST = 3; private const PRIVATE_CONST = 4; }

 

5.iterable 僞類

如今引入了一個新的被稱爲iterable的僞類 (與callable相似)。 這能夠被用在參數或者返回值類型中,它表明接受數組或者實現了Traversable接口的對象。 至於子類,當用做參數時,子類能夠收緊父類的iterable類型到array 或一個實現了Traversable的對象。對於返回值,子類能夠拓寬父類的 array或對象返回值類型到iterable。安全

function iterator(iterable $iter) { foreach ($iter as $val) { // } }

 

6.多異常捕獲處理

一個catch語句塊如今能夠經過管道字符(|)來實現多個異常的捕獲。 這對於須要同時處理來自不一樣類的不一樣異常時頗有用。bash

try { // some code } catch (FirstException | SecondException $e) { // handle first and second exceptions } catch (\Exception $e) { // ... }

 

7.list()如今支持鍵名

如今list()支持在它內部去指定鍵名。這意味着它能夠將任意類型的數組 都賦值給一些變量(與短數組語法相似)服務器

$data = [ ['id' => 1, 'name' => 'Tom'], ['id' => 2, 'name' => 'Fred'], ]; while (list('id' => $id, 'name' => $name) = $data) { // logic here with $id and $name }

 

8.支持爲負的字符串偏移量

如今全部接偏移量的內置的基於字符串的函數都支持接受負數做爲偏移量,包括數組解引用操做符([]).

var_dump("abcdef"[-2]); var_dump(strpos("aabbcc", "b", -3));

 

以上例程會輸出:

string (1) "e" int(3)

 

9.ext/openssl 支持 AEAD

經過給openssl_encrypt()和openssl_decrypt() 添加額外參數,如今支持了AEAD (模式 GCM and CCM)。 
經過 Closure::fromCallable() 將callables轉爲閉包 
Closure新增了一個靜態方法,用於將callable快速地 轉爲一個Closure 對象。

class Test { public function exposeFunction() { return Closure::fromCallable([$this, 'privateFunction']); } private function privateFunction($param) { var_dump($param); } } $privFunc = (new Test)->exposeFunction(); $privFunc('some value');

 

以上例程會輸出:

string(10) "some value"
  • 1
  • 1

10.異步信號處理 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). 
增長了一個新函數 pcntl_async_signals()來處理異步信號,不須要再使用ticks(它會增長佔用資源)

pcntl_async_signals(true); // turn on async signals pcntl_signal(SIGHUP, function($sig) { echo "SIGHUP\n"; }); posix_kill(posix_getpid(), SIGHUP);

 

以上例程會輸出:

SIGHUP

 

11.HTTP/2 服務器推送支持 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. 
蹩腳英語: 
對於服務器推送支持添加到curl擴展(須要7.46及以上版本)。 
能夠經過用新的CURLMOPT_PUSHFUNCTION常量 讓curl_multi_setopt()函數使用。 
也增長了常量CURL_PUST_OK和CURL_PUSH_DENY,能夠批准或拒絕 服務器推送回調的執行

不兼容性

1.當傳遞參數過少時將拋出錯誤

在過去若是咱們調用一個用戶定義的函數時,提供的參數不足,那麼將會產生一個警告(warning)。 如今,這個警告被提高爲一個錯誤異常(Error exception)。這個變動僅對用戶定義的函數生效, 並不包含內置函數。例如:

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.禁止動態調用函數

禁止動態調用函數以下 
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 算法修復

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.在不完整的對象上再也不調用析構方法

析構方法在一個不完整的對象(例如在構造方法中拋出一個異常)上將再也不會被調用

10.call_user_func()再也不支持對傳址的函數的調用

call_user_func() 如今在調用一個以引用做爲參數的函數時將始終失敗。

11.字符串再也不支持空索引操做符 The empty index operator is not supported for strings anymore

對字符串使用一個空索引操做符(例如str[]=x)將會拋出一個致命錯誤, 而不是靜默地將其轉爲一個數組

12.ini配置項移除

下列ini配置項已經被移除: 
session.entropy_file 
session.entropy_length 
session.hash_function 
session.hash_bits_per_character

PHP 7.1.x 中廢棄的特性

1.ext/mcrypt

mcrypt 擴展已通過時了大約10年,而且用起來很複雜。所以它被廢棄而且被 OpenSSL 所取代。 從PHP 7.2起它將被從核心代碼中移除而且移到PECL中。

2.mb_ereg_replace()和mb_eregi_replace()的Eval選項

對於mb_ereg_replace()和mb_eregi_replace()的 e模式修飾符如今已被廢棄

=====================================

PHP7.0

新特性

1.空合併運算符(??)

簡化判斷

$param = $_GET['param'] ?? 1;

 

至關於:

$param = isset($_GET['param']) ? $_GET['param'] : 1;

 

2.變量類型聲明

兩種模式 : 強制 ( 默認 ) 和 嚴格模式 
類型:string、int、float和 bool

function add(int $a) { return 1+$a; } var_dump(add(2); 

 

3.返回值類型聲明

函數和匿名函數均可以指定返回值的類型

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); }

 

4.太空船操做符(組合比較符)

太空船操做符用於比較兩個表達式。當 ab 時它分別返回 -1 、 0 或 1 。 比較的原則是沿用 PHP 的常規比較規則進行的。

// Integers echo 1 <=> 1; // 0 echo 1 <=> 2; // -1 echo 2 <=> 1; // 1 // Floats echo 1.5 <=> 1.5; // 0 echo 1.5 <=> 2.5; // -1 echo 2.5 <=> 1.5; // 1 // Strings echo "a" <=> "a"; // 0 echo "a" <=> "b"; // -1 echo "b" <=> "a"; // 1

 

5.匿名類

如今支持經過 new class 來實例化一個匿名類,這能夠用來替代一些「用後即焚」的完整類定義。

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());

 

6.Unicode codepoint 轉譯語法

這接受一個以16進制形式的 Unicode codepoint,並打印出一個雙引號或heredoc包圍的 UTF-8 編碼格式的字符串。 能夠接受任何有效的 codepoint,而且開頭的 0 是能夠省略的。

echo "\u{9876}"
  • 1
  • 1

舊版輸出:\u{9876} 
新版輸入:頂

7.Closure::call()

Closure::call() 如今有着更好的性能,簡短幹練的暫時綁定一個方法到對象上閉包並調用它。

class Test { public $name = "lixuan"; } //PHP7和PHP5.6均可以 $getNameFunc = function () { return $this->name; }; $name = $getNameFunc->bindTo(new Test, 'Test'); echo $name(); //PHP7能夠,PHP5.6報錯 $getX = function () { return $this->name; }; echo $getX->call(new Test);

 

8.爲unserialize()提供過濾

這個特性旨在提供更安全的方式解包不可靠的數據。它經過白名單的方式來防止潛在的代碼注入。

//將全部對象分爲__PHP_Incomplete_Class對象 $data = unserialize($foo, ["allowed_classes" => false]); //將全部對象分爲__PHP_Incomplete_Class 對象 除了ClassName1和ClassName2 $data = unserialize($foo, ["allowed_classes" => ["ClassName1", "ClassName2"]); //默認行爲,和 unserialize($foo)相同 $data = unserialize($foo, ["allowed_classes" => true]);

 

9.IntlChar

新增長的 IntlChar 類旨在暴露出更多的 ICU 功能。這個類自身定義了許多靜態方法用於操做多字符集的 unicode 字符。Intl是Pecl擴展,使用前須要編譯進PHP中,也可apt-get/yum/port install php5-intl

printf('%x', IntlChar::CODEPOINT_MAX); echo IntlChar::charName('@'); var_dump(IntlChar::ispunct('!'));

 

以上例程會輸出: 
10ffff 
COMMERCIAL AT 
bool(true)

10.預期

預期是向後兼用並加強以前的 assert() 的方法。 它使得在生產環境中啓用斷言爲零成本,而且提供當斷言失敗時拋出特定異常的能力。 老版本的API出於兼容目的將繼續被維護,assert()如今是一個語言結構,它容許第一個參數是一個表達式,而不只僅是一個待計算的 string或一個待測試的boolean。

ini_set('assert.exception', 1); class CustomError extends AssertionError {} assert(false, new CustomError('Some error message'));

 

以上例程會輸出: 
Fatal error: Uncaught CustomError: Some error message

11.Group use declarations

從同一 namespace 導入的類、函數和常量如今能夠經過單個 use 語句 一次性導入了。

//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};

 

12.intdiv()

接收兩個參數做爲被除數和除數,返回他們相除結果的整數部分。

var_dump(intdiv(7, 2));
  • 1
  • 1

輸出int(3)

13.CSPRNG

新增兩個函數: random_bytes() and random_int().能夠加密的生產被保護的整數和字符串。總之隨機數變得安全了。 
random_bytes — 加密生存被保護的僞隨機字符串 
random_int —加密生存被保護的僞隨機整數

1四、preg_replace_callback_array()

新增了一個函數preg_replace_callback_array(),使用該函數可使得在使用preg_replace_callback()函數時代碼變得更加優雅。在PHP7以前,回調函數會調用每個正則表達式,回調函數在部分分支上是被污染了。

1五、Session options

如今,session_start()函數能夠接收一個數組做爲參數,能夠覆蓋php.ini中session的配置項。 
好比,把cache_limiter設置爲私有的,同時在閱讀完session後當即關閉。

session_start(['cache_limiter' => 'private', 'read_and_close' => true, ]);

 

1六、生成器的返回值

在PHP5.5引入生成器的概念。生成器函數每執行一次就獲得一個yield標識的值。在PHP7中,當生成器迭代完成後,能夠獲取該生成器函數的返回值。經過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

1七、生成器中引入其餘生成器

在生成器中能夠引入另外一個或幾個生成器,只須要寫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

18.經過define()定義常量數組

define('ANIMALS', ['dog', 'cat', 'bird']); echo ANIMALS[1]; // outputs "cat"
  • 1
  • 2
  • 1
  • 2

不兼容性

一、foreach再也不改變內部數組指針

在PHP7以前,當數組經過 foreach 迭代時,數組指針會移動。如今開始,再也不如此,見下面代碼。

$array = [0, 1, 2]; foreach ($array as &$val) { var_dump(current($array)); }
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

PHP5輸出: 
int(1) 
int(2) 
bool(false) 
PHP7輸出: 
int(0) 
int(0) 
int(0)

二、foreach經過引用遍歷時,有更好的迭代特性

當使用引用遍歷數組時,如今 foreach 在迭代中能更好的跟蹤變化。例如,在迭代中添加一個迭代值到數組中,參考下面的代碼:

$array = [0]; foreach ($array as &$val) { var_dump($val); $array[1] = 1; }

 

PHP5輸出: 
int(0) 
PHP7輸出: 
int(0) 
int(1)

三、十六進制字符串再也不被認爲是數字

含十六進制字符串再也不被認爲是數字

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」

四、PHP7中被移除的函數

被移除的函數列表以下: 
call_user_func() 和 call_user_func_array()從PHP 4.1.0開始被廢棄。 
已廢棄的 mcrypt_generic_end() 函數已被移除,請使用mcrypt_generic_deinit()代替。 
已廢棄的 mcrypt_ecb(), mcrypt_cbc(), mcrypt_cfb() 和 mcrypt_ofb() 函數已被移除。 
set_magic_quotes_runtime(), 和它的別名 magic_quotes_runtime()已被移除. 它們在PHP 5.3.0中已經被廢棄,而且 在in PHP 5.4.0也因爲魔術引號的廢棄而失去功能。 
已廢棄的 set_socket_blocking() 函數已被移除,請使用stream_set_blocking()代替。 
dl()在 PHP-FPM 再也不可用,在 CLI 和 embed SAPIs 中仍可用。 
GD庫中下列函數被移除:imagepsbbox()、imagepsencodefont()、imagepsextendfont()、imagepsfreefont()、imagepsloadfont()、imagepsslantfont()、imagepstext() 
在配置文件php.ini中,always_populate_raw_post_data、asp_tags、xsl.security_prefs被移除了。

五、new 操做符建立的對象不能以引用方式賦值給變量

new 操做符建立的對象不能以引用方式賦值給變量

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

六、移除了 ASP 和 script PHP 標籤

使用相似 ASP 的標籤,以及 script 標籤來區分 PHP 代碼的方式被移除。 受到影響的標籤有:<% %>、<%= %>、

七、從不匹配的上下文發起調用

在不匹配的上下文中以靜態方式調用非靜態方法, 在 PHP 5.6 中已經廢棄, 可是在 PHP 7.0 中, 會致使被調用方法中未定義 $this 變量,以及此行爲已經廢棄的警告。

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

八、在數值溢出的時候,內部函數將會失敗

將浮點數轉換爲整數的時候,若是浮點數值太大,致使沒法以整數表達的狀況下, 在以前的版本中,內部函數會直接將整數截斷,並不會引起錯誤。 在 PHP 7.0 中,若是發生這種狀況,會引起 E_WARNING 錯誤,而且返回 NULL。

九、JSON 擴展已經被 JSOND 取代

JSON 擴展已經被 JSOND 擴展取代。 
對於數值的處理,有如下兩點須要注意的: 
第一,數值不能以點號(.)結束 (例如,數值 34. 必須寫做 34.0 或 34)。 
第二,若是使用科學計數法表示數值,e 前面必須不是點號(.) (例如,3.e3 必須寫做 3.0e3 或 3e3)。

十、INI 文件中 # 註釋格式被移除

在配置文件INI文件中,再也不支持以 # 開始的註釋行, 請使用 ;(分號)來表示註釋。 此變動適用於 php.ini 以及用 parse_ini_file() 和 parse_ini_string() 函數來處理的文件。

十一、$HTTP_RAW_POST_DATA 被移除

再也不提供 $HTTP_RAW_POST_DATA 變量。 請使用 php://input 做爲替代。

十二、yield 變動爲右聯接運算符

在使用 yield 關鍵字的時候,再也不須要括號, 而且它變動爲右聯接操做符,其運算符優先級介於 print 和 => 之間。 這可能致使現有代碼的行爲發生改變。能夠經過使用括號來消除歧義。

echo yield -1; // 在以前版本中會被解釋爲: echo (yield) - 1; // 如今,它將被解釋爲: echo yield (-1); yield $foo or die; // 在以前版本中會被解釋爲: yield ($foo or die); // 如今,它將被解釋爲: (yield $foo) or die;
相關文章
相關標籤/搜索