PHP7.0新增功能詳解(實例)

2019-11-01   科技i關注



這一篇主要是來詳細分析php7.0的新增功能。

一、性能與底層

PHP7速度是 PHP5.6 的兩倍

php7 最顯著的變化就是性能的極大提升,已接近Facebook開發的PHP執行引擎HHVM。在WordPress基準性能測試中,速度比5.6版本要快2~3倍,大大減少了內存占用。PHP7在語言上也有一些變化,比如添加返回類型聲明、增加了一些新的保留關鍵字等。在安全方面,去除了PHP安全模式,添加魔術引號等。不僅如此,新版還支持64位,而且包含最新版Zend引擎。

測試一下

很簡單的一個例子,生成一個 60 萬元素的數組,通過查找key 的方式,來確定key是否存在。

$a = [];

for($i=0;$i<600000;$i++){

$a[$i] = $i;

}

foreach($a as $item) {

array_key_exists($item, $a);

}

我們分別在php5.6.11和php7.0.4來測試下性能。

php5.6.11

time php 1.php

0.67s user 0.06s system 67% cpu 1.078 total

time php 1.php

0.68s user 0.06s system 98% cpu 0.748 total

time php 1.php

0.65s user 0.06s system 67% cpu 1.052 total

三次平均下來,大致是 user使用 0.65秒,system使用0.06秒,67%的cpu率。總共1秒左右。

再看php7的情況

time /usr/local/opt/php70/bin/php 1.php

0.52s user 0.02s system 98% cpu 0.544 total

time /usr/local/opt/php70/bin/php 1.php

0.49s user 0.02s system 99% cpu 0.513 total

time /usr/local/opt/php70/bin/php 1.php

0.51s user 0.02s system 98% cpu 0.534 total

對比下來,user使用時間下降20%左右,system使用時間下降70%,cpu使用率更高高達98%。總體時間減少為。0.5秒。

這個例子看下來,效率提供了2倍。確實不錯。

再看一個例子。同樣也是生成一個 60 萬元素的數組,查找 value是否存在。

$a = [];

for($i=0;$i<600000;$i++){

$a[$i] = $i;

}

foreach($a as $i) {

array_search($i, $a);

}

?>

先看php5.6.11

testPHP time php 2.php

0.68s user 0.03s system 66% cpu 1.077 total

testPHP time php 2.php

0.68s user 0.02s system 98% cpu 0.710 total

testPHP time php 2.php

0.68s user 0.02s system 98% cpu 0.713 total

testPHP time php 2.php

0.69s user 0.02s system 98% cpu 0.721 total

再接著看php7.0.4

testPHP time /usr/local/opt/php70/bin/php 2.php

0.12s user 0.02s system 69% cpu 0.201 total

testPHP time /usr/local/opt/php70/bin/php 2.php

0.11s user 0.01s system 97% cpu 0.131 total

testPHP time /usr/local/opt/php70/bin/php 2.php

0.11s user 0.01s system 96% cpu 0.130 total

明顯看出,快了6倍多。厲害。

二、新特性

1. 更多的標量類型聲明

現在php的標量有兩種模式: 強制 (默認) 和嚴格模式。 現在可以使用下列類型參數(無論用強制模式還是嚴格模式): 字符串(string), 整數 (int), 浮點數 (float), 以及布爾值 (bool)。它們擴充了PHP5中引入的其他類型:類名,接口,數組和 回調類型。在舊版中,函數的參數申明只能是(Array $arr)、(CLassName $obj)等,基本類型比如Int,String等是不能夠被申明的。

怎麼理解呢?php7之前的版本,我們要想限定一個函數的參數的類型,只有array或者class2種。

php7之前:

class MyInfo

{

public $a = 123;

public function getInfo(array $a, $b)

{

var_dump($a, $b);

}

}

function getClass(MyInfo $a) {

var_dump($a->a);

}

我們想限定 getInfo的第一個參數,必須是數組,所以,我們可以在參數$a前加一個array。來申明。

同樣,我們想getClass的參數,必須是一個類,所以我們就用這個類的className前墜來申明,起到強制使用的目的。

php7之前,只有這2種標量可以使用。

我們來使用一下:

$info = new MyInfo();

$info->getInfo([1,2,3,4], 4);

我們按照規定的來,第一個參數,傳數組,結果當然是正常列印:

testPHP php 3.php

array(3) {

[0] =>

int(1)

[1] =>

int(2)

[2] =>

int(3)

}

int(4)

要是我們不安裝規定來,就會報知名錯誤:

$info = new MyInfo();

$info->getInfo(122, 0);

報錯:

PHP Catchable fatal error: Argument 1 passed to MyInfo::getInfo() must be of the type array, integer given, called in /Users/yangyi/www/testPHP/3.php on line 25 and defined in /Users/yangyi/www/testPHP/3.php on line 8

PHP Stack trace:

PHP 1. {main}() /Users/yangyi/www/testPHP/3.php:0

PHP 2. MyInfo->getInfo() /Users/yangyi/www/testPHP/3.php:25

使用類也一樣:

$info = new MyInfo();

getClass($info);

輸出結果:

testPHP php 3.php

int(123)

同樣,我們傳入別的參數,就會報錯:

getClass(123);

testPHP php 3.php

PHP Catchable fatal error: Argument 1 passed to getClass() must be an instance of MyInfo, integer given, called in /Users/yangyi/www/testPHP/3.php on line 27 and defined in /Users/yangyi/www/testPHP/3.php on line 17

PHP Stack trace:

PHP 1. {main}() /Users/yangyi/www/testPHP/3.php:0

PHP 2. getClass() /Users/yangyi/www/testPHP/3.php:27

我們回到這次php7的升級,它擴充了標量的類型,增加了bool、int、string、float。

php7有2種兩種模式: 強制 (默認) 和嚴格模式。

強制模式

強制模式是默認模式,強制模式下,它會幫我們把數字類型的string類型,int整型,bool,強制類型。其他類型不能轉換,就會報錯。

還是剛才的例子:

class MyInfo

{

public $a = 123;

public function get1(bool $b)

{

var_dump($b);

}

public function get2(int $b)

{

var_dump($b);

}

public function get3(string $b)

{

var_dump($b);

}

public function get4(float $b)

{

var_dump($b);

}

public function get5(array $b)

{

var_dump($b);

}

}

我們先全部傳入int 1

$info = new MyInfo();

$info->get1(1);

$info->get2(1);

$info->get3(1);

$info->get4(1);

看列印結果,它已經幫我們強制轉換了。

testPHP /usr/local/opt/php70/bin/php 3.php

/Users/yangyi/www/testPHP/3.php:11:

bool(true)

/Users/yangyi/www/testPHP/3.php:19:

int(1)

/Users/yangyi/www/testPHP/3.php:26:

string(1) "1"

/Users/yangyi/www/testPHP/3.php:33:

double(1)

我們繼續,傳入 string 1.23 :

$info = new MyInfo();

$info->get1('1.23');

$info->get2('1.23');

$info->get3('1.23');

$info->get4('1.23');

看下,列印結果。也已經幫我們強制轉換了。

testPHP /usr/local/opt/php70/bin/php 3.php

/Users/yangyi/www/testPHP/3.php:11:

bool(true)

/Users/yangyi/www/testPHP/3.php:19:

int(1)

/Users/yangyi/www/testPHP/3.php:26:

string(4) "1.23"

/Users/yangyi/www/testPHP/3.php:33:

double(1.23)

但是我們如果參數是array就沒法強制轉換,就會報錯了:

$info->get5('1.23');

testPHP /usr/local/opt/php70/bin/php 3.php

PHP Fatal error: Uncaught TypeError: Argument 1 passed to MyInfo::get5() must be of the type array, string given, called in /Users/yangyi/www/testPHP/3.php on line 54 and defined in /Users/yangyi/www/testPHP/3.php:37

我們在PHP5.6.11運行這些代碼會報錯嗎?試一試:

$info = new MyInfo();

$info->get1('1.23');

$info->get2('1.23');

$info->get3('1.23');

$info->get4('1.23');

testPHP php 3.php

PHP Catchable fatal error: Argument 1 passed to MyInfo::get1() must be an instance of bool, string given, called in /Users/yangyi/www/testPHP/3.php on line 48 and defined in /Users/yangyi/www/testPHP/3.php on line 8

好吧。直接報錯了,雖然錯誤提示也是說類型錯誤,但是,其他是不支持這些類型的申明。

嚴格模式

前面說了,強制模式下,它會幫我們強制轉換,那麼嚴格模式下呢?

首先,如何打開嚴格模式呢?

declare(strict_types=1);

加上就可以了,這樣,就進入嚴格模式,參數必須符合規定,不然報錯:

我們加上這句話,再運行下:

declare(strict_types=1);

...

...

$info = new MyInfo();

$info->get1('1.23');

$info->get2('1.23');

$info->get3('1.23');

$info->get4('1.23');

運行,看下結果,果然直接報錯了。

PHP Fatal error: Uncaught TypeError: Argument 1 passed to MyInfo::get1() must be of the type boolean, string given, called in /Users/yangyi/www/testPHP/3.php on line 49 and defined in /Users/yangyi/www/testPHP/3.php:9

2. 返回值類型聲明

我們知道php的函數是沒有返回值類型的,return啥類型,就是啥類型。php7中增加了返回值類型,我們可以定義一個函數的返回值類型。

和php7升級的標量類型聲明一樣,return的類型可以是以下這些:bool、int、string、float、array、class。

舉個例子來說,我們希望一個函數的返回值是一個數組,我們可以這樣子書寫:

:array {} // 冒號+返回類型

function returnInfo ($a) : array {

return $a;

}

var_dump(returnInfo([1,2,3]));

是不是覺得很奇怪,又無可思議!!!

查看列印結果:

testPHP /usr/local/opt/php70/bin/php 3.php

/Users/yangyi/www/testPHP/3.php:64:

array(3) {

[0] =>

int(1)

[1] =>

int(2)

[2] =>

int(3)

}

同樣,我們想返回是int整型:

function returnInfo ($a) : int {

return $a;

}

var_dump(returnInfo('1.233'));

查看結果,他已經幫我們強制轉換成整型了。

testPHP /usr/local/opt/php70/bin/php 3.php

/Users/yangyi/www/testPHP/3.php:64:

int(1)

同樣,我們可以返回一個class類型的:

public function getLogger(): Logger {

return $this->logger;

}

默認,也是強制模式,會幫我們轉換,如果,我們想使用嚴格模式,同樣是一樣的,在文件頭部加上:

declare(strict_types=1);

就可以了,這樣,我們規定返回值是什麼類型,就必須得是這樣,不然就報致命報錯。

3. null合併運算符 (??)

由於日常使用中存在大量同時使用三元表達式和 isset()的情況, php7增加了一個新的語法糖 : null合併運算符 (??)

如果變量存在且值不為NULL, 它就會返回自身的值,否則返回它的第二個操作數。

//php version = 7

$username = $user ?? 'nobody';

//php version < 7 得這樣使用:

$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

確實方便了很多。

我記得php5.3的更新中,加入了 三元運算符簡寫形式:

$a ?: $b

千萬別和??搞混淆了!!!

$a ?: $b的意思是 $a為true時,直接返回$a, 否則返回$b

$a ?? $b的意思是 $a isset($a)為true, 且不為NULL, 就返回$a, 否則返回$b。

看例子:

$user = 0;

$username = $user ?? 'nobody';

echo $username; //輸出 0,因為 0 存在 且 不為NULL。

$username = $user ?: 'nobody';

echo $username; //輸出 'nobody',因為 0 為 false

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

php7 中,新加入了一個比較符號:<=> ,因為長相像太空船,所以,也叫太空船操作符。

它有啥用呢?

<=>用於比較兩個表達式。當$a小於、等於或大於$b時它分別返回-1、0或1。

看例子:

// 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. 通過define()定義常量數組

Array類型的常量現在可以通過 define()來定義。在 PHP5.6 中僅能通過const定義。

在php5.3中,增加了可以使用const來申明常量,替代define()函數,但是只能申明一些簡單的變量。

//舊式風格:

define("XOOO", "Value");

//新式風格:

const XXOO = "Value";

//const 形式僅適用於常量,不適用於運行時才能求值的表達式:

// 正確

const XXOO = 1234;

// 錯誤

const XXOO = 2 * 617;

在php5.6中,又對const進行來升級,可以支持上面的運算了。

const A = 2;

const B = A + 1;

但是,一隻都是在優化const,可是確把define()給搞忘記了,php 5.6申明一個數組常量,只能用const。所以,在 php7 中把 define()申明一個數組也給加上去了。

//php 7

define ('AWS' , [12,33,44,55]);

// php < 7

const QWE = [12,33,44,55];

echo AWS[1]; //12

echo QWE[2]; //33

至此,到php7版本,define()的功能和const就一摸一樣了,所以,你隨便用哪一個都可以,但是因為在class類中,什麼常量是const。所以,我們就統一用const申明常量好了。

6. 匿名類

現在已經支持通過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());

?>

我們先輸出的列印的結果,顯示為匿名類:

class class@anonymous#2 (0) {

}

我們來分解下,還原被偷懶的少寫的代碼:

class logClass implements Logger {

public function log(string $msg) {

echo $msg;

}

}

$app = new Application;

$log2 = new logClass;

$app->setLogger($log2);

輸出結果為:

class logClass#2 (0) {

}

雖然代碼簡潔了很多,但是還是有點不適應,多用用就好了。

還記得php中的匿名函數嘛?在php5.3中新增的匿名函數,結合新的,順便複習下:

function arraysSum(array ...$arrays): array {

return array_map(function(array $array): int {

return array_sum($array);

}, $arrays);

}

print_r(arraysSum([1,2,3], [4,5,6], [7,8,9]));

輸出結果為:

Array

(

[0] => 6

[1] => 15

[2] => 24

)

7. Unicode codepoint 轉譯語法

ps : 由於用的少,我就直接抄官網的說明了。

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

echo "\\\\u{0000aa}";

echo "\\\\u{aa}"; //省略了開頭的0

echo "\\\\u{9999}";

看下輸出:

ª ª 香

我們在php5.6環境下執行下呢?會怎樣:

\\\\u{aa} \\\\u{0000aa} \\\\u{9999}

好吧,直接原樣輸出了。

8. Closure::call() 閉包

ps : 由於用的少,我就直接抄官網的說明了。

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

class A {private $x = 1;}

// php 7之前:

$getXCB = function() {return $this->x;};

$getX = $getXCB->bindTo(new A, 'A'); // intermediate closure

echo $getX();

// PHP 7:

$getX = function() {return $this->x;};

echo $getX->call(new A);

會輸出:

1

1

9. 為unserialize()提供過濾

unserialize 這個函數應該不陌生,它是php中用解開用serialize序列化的變量。

看個栗子:

$a = [1,2,3,4,5,6];

$b = serialize($a);

$c = unserialize($b);

var_dump($a, $b, $c);

列印結果為:

array(6) {

[0] =>

int(1)

[1] =>

int(2)

[2] =>

int(3)

[3] =>

int(4)

[4] =>

int(5)

[5] =>

int(6)

}

string(54) "a:6:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;i:4;i:5;i:5;i:6;}"

array(6) {

[0] =>

int(1)

[1] =>

int(2)

[2] =>

int(3)

[3] =>

int(4)

[4] =>

int(5)

[5] =>

int(6)

}

現在php7中unserialize會變得更佳好用,它多了一個參數,用來反序列化包涵class的過濾不需要的類,變的更加安全。

unserialize($one, ["allowed_classes" => true]);

unserialize($one, ["allowed_classes" => false]);

unserialize($one, ["allowed_classes" => [class1,class2,class3]]);

舉個例子,先序列化一個類。

class MyInfo {

public function getMyName()

{

return 'phper';

}

}

$phper = new MyInfo();

$one = serialize($phper);

//參數allowed_classes 設置為 true,表示允許解析class

$two = unserialize($one, ["allowed_classes" => true]);

//參數allowed_classes 設置為 false,表示不允許解析class

$three = unserialize($one, ["allowed_classes" => false]);

//不加參數。正常解析。

$four = unserialize($one);

//只允許解析 類 MyInfo1。

$five = unserialize($one, ["allowed_classes" => ["MyInfo1"]]);

//分別輸出下 getMyName方法;

var_dump($one);

var_dump($two->getMyName());

var_dump($three->getMyName());

var_dump($four->getMyName());

var_dump($five->getMyName());

發現3和5直接報致命錯誤了:

PHP Fatal error: main(): The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition "MyInfo" of the object you are trying to operate on was loaded _before_ unserialize() gets called or provide a __autoload() function to load the class definition in /Users/yangyi/www/php7/5.php on line 22

大致意思就是,沒權限解析。

所以,我們改一下:

$three = unserialize($one, ["allowed_classes" => true]);

$five = unserialize($one, ["allowed_classes" => ["MyInfo"]]);

再輸出,就正常了。

/Users/yangyi/www/php7/5.php:22:

string(17) "O:6:"MyInfo":0:{}"

/Users/yangyi/www/php7/5.php:23:

string(5) "phper"

/Users/yangyi/www/php7/5.php:24:

string(5) "phper"

/Users/yangyi/www/php7/5.php:25:

string(5) "phper"

/Users/yangyi/www/php7/5.php:26:

string(5) "phper"

發現我目前為止並沒用到,並沒有什麼亂用,好吧,繼續下一個。

10. IntlChar

ps : 由於用的少,我就直接抄官網的說明了。

新增加的 IntlChar(http://php.net/manual/zh/class.intlchar.php) 類旨在暴露出更多的 ICU 功能。這個類自身定義了許多靜態方法用於操作多字符集的 unicode 字符。

printf('%x', IntlChar::CODEPOINT_MAX);

echo IntlChar::charName('@');

var_dump(IntlChar::ispunct('!'));

以上例程會輸出:

10ffff

COMMERCIAL AT

bool(true)

若要使用此類,請先安裝Intl擴展

相關推薦:《PHP7新特性手冊》

以上就是PHP7.0新增功能詳解(實例)的詳細內容,更多請關注其它相關文章!

更多技巧請《轉發 + 關注》哦!