PHP7.0新增功能详解(实例)(调用接口前端调用新增和修改接口)
這一篇主要是來詳細分析php7.0的新增功能。
一、性能與底層
PHP7速度是 PHP5.6 的兩倍
php7 最顯著的變化就是性能的極大提升,已接近Facebook開發(fā)的PHP執(zhí)行引擎HHVM。在WordPress基準性能測試中,速度比5.6版本要快2~3倍,大大減少了內(nèi)存占用。PHP7在語言上也有一些變化,比如添加返回類型聲明、增加了一些新的保留關鍵字等。在安全方面,去除了PHP安全模式,添加魔術引號等。不僅如此,新版還支持64位,而且包含最新版Zend引擎。
測試一下
很簡單的一個例子,生成一個 60 萬元素的數(shù)組,通過查找key 的方式,來確定key是否存在。
<?php
$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率??偣?秒左右。
再看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%??傮w時間減少為。0.5秒。
這個例子看下來,效率提供了2倍。確實不錯。
再看一個例子。同樣也是生成一個 60 萬元素的數(shù)組,查找 value是否存在。
<?php
$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. 更多的標量類型聲明
現(xiàn)在php的標量有兩種模式: 強制 (默認) 和嚴格模式。 現(xiàn)在可以使用下列類型參數(shù)(無論用強制模式還是嚴格模式): 字符串(string), 整數(shù) (int), 浮點數(shù) (float), 以及布爾值 (bool)。它們擴充了PHP5中引入的其他類型:類名,接口,數(shù)組和 回調(diào)類型。在舊版中,函數(shù)的參數(shù)申明只能是(Array $arr)、(CLassName $obj)等,基本類型比如Int,String等是不能夠被申明的。
怎么理解呢?php7之前的版本,我們要想限定一個函數(shù)的參數(shù)的類型,只有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的第一個參數(shù),必須是數(shù)組,所以,我們可以在參數(shù)$a前加一個array。來申明。
同樣,我們想getClass的參數(shù),必須是一個類,所以我們就用這個類的className前墜來申明,起到強制使用的目的。
php7之前,只有這2種標量可以使用。
我們來使用一下:
$info = new MyInfo(); $info->getInfo([1,2,3,4], 4);
登錄后復制
我們按照規(guī)定的來,第一個參數(shù),傳數(shù)組,結果當然是正常打印:
? testPHP php 3.php
array(3) {
[0] =>
int(1)
[1] =>
int(2)
[2] =>
int(3)
}
int(4)
登錄后復制
要是我們不安裝規(guī)定來,就會報知名錯誤:
$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)
登錄后復制
同樣,我們傳入別的參數(shù),就會報錯:
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種兩種模式: 強制 (默認) 和嚴格模式。
強制模式
強制模式是默認模式,強制模式下,它會幫我們把數(shù)字類型的string類型,int整型,bool,強制類型。其他類型不能轉(zhuǎn)換,就會報錯。
還是剛才的例子:
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);
登錄后復制
看打印結果,它已經(jīng)幫我們強制轉(zhuǎn)換了。
? 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)
登錄后復制
我們繼續(xù),傳入 string 1.23 :
$info = new MyInfo();
$info->get1('1.23');
$info->get2('1.23');
$info->get3('1.23');
$info->get4('1.23');
登錄后復制
看下,打印結果。也已經(jīng)幫我們強制轉(zhuǎn)換了。
? 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)
登錄后復制
但是我們?nèi)绻麉?shù)是array就沒法強制轉(zhuǎn)換,就會報錯了:
$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
登錄后復制
好吧。直接報錯了,雖然錯誤提示也是說類型錯誤,但是,其他是不支持這些類型的申明。
嚴格模式
前面說了,強制模式下,它會幫我們強制轉(zhuǎn)換,那么嚴格模式下呢?
首先,如何打開嚴格模式呢?
<?php declare(strict_types=1);
登錄后復制登錄后復制
加上就可以了,這樣,就進入嚴格模式,參數(shù)必須符合規(guī)定,不然報錯:
我們加上這句話,再運行下:
<?php
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的函數(shù)是沒有返回值類型的,return啥類型,就是啥類型。php7中增加了返回值類型,我們可以定義一個函數(shù)的返回值類型。
和php7升級的標量類型聲明一樣,return的類型可以是以下這些:bool、int、string、float、array、class。
舉個例子來說,我們希望一個函數(shù)的返回值是一個數(shù)組,我們可以這樣子書寫:
:array {} // 冒號+返回類型
function returnInfo ($a) : array {
return $a;
}
var_dump(returnInfo([1,2,3]));
登錄后復制
是不是覺得很奇怪,又無可思議?。。?/p>
查看打印結果:
? 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'));
登錄后復制
查看結果,他已經(jīng)幫我們強制轉(zhuǎn)換成整型了。
? 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;
}
登錄后復制
默認,也是強制模式,會幫我們轉(zhuǎn)換,如果,我們想使用嚴格模式,同樣是一樣的,在文件頭部加上:
<?php declare(strict_types=1);
登錄后復制登錄后復制
就可以了,這樣,我們規(guī)定返回值是什么類型,就必須得是這樣,不然就報致命報錯。
3. null合并運算符 (??)
由于日常使用中存在大量同時使用三元表達式和 isset()的情況, php7增加了一個新的語法糖 : null合并運算符 (??)
如果變量存在且值不為NULL, 它就會返回自身的值,否則返回它的第二個操作數(shù)。
//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。
看例子:
<?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. 通過define()定義常量數(shù)組
Array類型的常量現(xiàn)在可以通過 define()來定義。在 PHP5.6 中僅能通過const定義。
在php5.3中,增加了可以使用const來申明常量,替代define()函數(shù),但是只能申明一些簡單的變量。
//舊式風格:
define("XOOO", "Value");
//新式風格:
const XXOO = "Value";
//const 形式僅適用于常量,不適用于運行時才能求值的表達式:
// 正確
const XXOO = 1234;
// 錯誤
const XXOO = 2 * 617;
登錄后復制
在php5.6中,又對const進行來升級,可以支持上面的運算了。
const A = 2; const B = A + 1;
登錄后復制
但是,一只都是在優(yōu)化const,可是確把define()給搞忘記了,php 5.6申明一個數(shù)組常量,只能用const。所以,在 php7 中把 define()申明一個數(shù)組也給加上去了。
//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。所以,我們就統(tǒng)一用const申明常量好了。
6. 匿名類
現(xiàn)在已經(jīng)支持通過new class 來實例化一個匿名類,這可以用來替代一些用后即焚的完整類定義。
看下這個官方文檔上的一個栗子:
<?php
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中的匿名函數(shù)嘛?在php5.3中新增的匿名函數(shù),結合新的,順便復習下:
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 轉(zhuǎn)譯語法
ps : 由于用的少,我就直接抄官網(wǎng)的說明了。
這接受一個以16進制形式的 Unicode codepoint,并打印出一個雙引號或heredoc包圍的 UTF-8 編碼格式的字符串。 可以接受任何有效的 codepoint,并且開頭的 0 是可以省略的。
echo "\u{0000aa}";
echo "\u{aa}"; //省略了開頭的0
echo "\u{9999}";
登錄后復制
看下輸出:
a a 香
登錄后復制
我們在php5.6環(huán)境下執(zhí)行下呢?會怎樣:
\u{aa} \u{0000aa} \u{9999}
登錄后復制
好吧,直接原樣輸出了。
8. Closure::call() 閉包
ps : 由于用的少,我就直接抄官網(wǎng)的說明了。
Closure::call() 現(xiàn)在有著更好的性能,簡短干練的暫時綁定一個方法到對象上閉包并調(diào)用它。
<?php
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 這個函數(shù)應該不陌生,它是php中用解開用serialize序列化的變量。
看個栗子:
<?php $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)
}
登錄后復制
現(xiàn)在php7中unserialize會變得更佳好用,它多了一個參數(shù),用來反序列化包涵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);
//參數(shù)allowed_classes 設置為 true,表示允許解析class
$two = unserialize($one, ["allowed_classes" => true]);
//參數(shù)allowed_classes 設置為 false,表示不允許解析class
$three = unserialize($one, ["allowed_classes" => false]);
//不加參數(shù)。正常解析。
$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());
登錄后復制
發(fā)現(xiàn)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"
登錄后復制
發(fā)現(xiàn)我目前為止并沒用到,并沒有什么亂用,好吧,繼續(xù)下一個。
10. IntlChar
ps : 由于用的少,我就直接抄官網(wǎng)的說明了。
新增加的 IntlChar(http://php.net/manual/zh/class.intlchar.php) 類旨在暴露出更多的 ICU 功能。這個類自身定義了許多靜態(tài)方法用于操作多字符集的 unicode 字符。
<?php
printf('%x', IntlChar::CODEPOINT_MAX);
echo IntlChar::charName('@');
var_dump(IntlChar::ispunct('!'));
登錄后復制
以上例程會輸出:
10ffff COMMERCIAL AT bool(true)
登錄后復制
若要使用此類,請先安裝Intl擴展
相關推薦:《PHP7新特性手冊》
以上就是PHP7.0新增功能詳解(實例)的詳細內(nèi)容,更多請關注風君子博客其它相關文章!
總結
以上是生活随笔為你收集整理的PHP7.0新增功能详解(实例)(调用接口前端调用新增和修改接口)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 个人申请小程序有什么功能
- 下一篇: 特斯拉股价开年暴跌超12%,市值蒸发近5