@phper
2018-01-10T03:31:37.000000Z
字数 11092
阅读 8059
php
这一篇主要是来详细分析php7.0的新增功能。
php7 最显著的变化就是性能的极大提升,已接近Facebook开发的PHP执行引擎HHVM。在WordPress基准性能测试中,速度比5.6版本要快2~3倍,大大减少了内存占用。PHP7在语言上也有一些变化,比如添加返回类型声明、增加了一些新的保留关键字等。在安全方面,去除了PHP安全模式,添加魔术引号等。不仅如此,新版还支持64位,而且包含最新版Zend引擎。
<?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.php0.67s user 0.06s system 67% cpu 1.078 total➜ time php 1.php0.68s user 0.06s system 98% cpu 0.748 total➜ time php 1.php0.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.php0.52s user 0.02s system 98% cpu 0.544 total➜ time /usr/local/opt/php70/bin/php 1.php0.49s user 0.02s system 99% cpu 0.513 total➜ time /usr/local/opt/php70/bin/php 1.php0.51s user 0.02s system 98% cpu 0.534 total
对比下来,user使用时间下降20%左右,system使用时间下降70%,cpu使用率更高高达98%。总体时间减少为。0.5秒。
这个例子看下来,效率提供了2倍。确实不错。
<?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.php0.68s user 0.03s system 66% cpu 1.077 total➜ testPHP time php 2.php0.68s user 0.02s system 98% cpu 0.710 total➜ testPHP time php 2.php0.68s user 0.02s system 98% cpu 0.713 total➜ testPHP time php 2.php0.69s user 0.02s system 98% cpu 0.721 total
再接着看php7.0.4
➜ testPHP time /usr/local/opt/php70/bin/php 2.php0.12s user 0.02s system 69% cpu 0.201 total➜ testPHP time /usr/local/opt/php70/bin/php 2.php0.11s user 0.01s system 97% cpu 0.131 total➜ testPHP time /usr/local/opt/php70/bin/php 2.php0.11s user 0.01s system 96% cpu 0.130 total
明显看出,快了6倍多。厉害。
现在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.phparray(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 8PHP Stack trace:PHP 1. {main}() /Users/yangyi/www/testPHP/3.php:0PHP 2. MyInfo->getInfo() /Users/yangyi/www/testPHP/3.php:25
使用类也一样:
$info = new MyInfo();getClass($info);
输出结果:
➜ testPHP php 3.phpint(123)
同样,我们传入别的参数,就会报错:
getClass(123);
➜ testPHP php 3.phpPHP 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 17PHP Stack trace:PHP 1. {main}() /Users/yangyi/www/testPHP/3.php:0PHP 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.phpPHP 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.phpPHP 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
好吧。直接报错了,虽然错误提示也是说类型错误,但是,其他是不支持这些类型的申明。
前面说了,强制模式下,它会帮我们强制转换,那么严格模式下呢?
首先,如何打开严格模式呢?
<?phpdeclare(strict_types=1);
加上就可以了,这样,就进入严格模式,参数必须符合规定,不然报错:
我们加上这句话,再运行下:
<?phpdeclare(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
我们知道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;}
默认,也是强制模式,会帮我们转换,如果,我们想使用严格模式,同样是一样的,在文件头部加上:
<?phpdeclare(strict_types=1);
就可以了,这样,我们规定返回值是什么类型,就必须得是这样,不然就报致命报错。
由于日常使用中存在大量同时使用三元表达式和 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
php7 中,新加入了一个比较符号:<=> ,因为长相像太空船,所以,也叫太空船操作符。
它有啥用呢?
<=>用于比较两个表达式。当$a小于、等于或大于$b时它分别返回-1、0或1。
看例子:
<?php// 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?>
其实,蛮多地方可以派上用场的。
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 7define ('AWS' , [12,33,44,55]);// php < 7const QWE = [12,33,44,55];echo AWS[1]; //12echo QWE[2]; //33
至此,到php7版本,define()的功能和const就一摸一样了,所以,你随便用哪一个都可以,但是因为在class类中,什么常量是const。所以,我们就统一用const申明常量好了。
现在已经支持通过new class 来实例化一个匿名类,这可以用来替代一些用后即焚的完整类定义。
看下这个官方文档上的一个栗子:
<?phpinterface 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)
ps : 由于用的少,我就直接抄官网的说明了。😊
这接受一个以16进制形式的 Unicode codepoint,并打印出一个双引号或heredoc包围的 UTF-8 编码格式的字符串。 可以接受任何有效的 codepoint,并且开头的 0 是可以省略的。
echo "\u{0000aa}";echo "\u{aa}"; //省略了开头的0echo "\u{9999}";
看下输出:
ª ª 香
我们在php5.6环境下执行下呢?会怎样:
\u{aa} \u{0000aa} \u{9999}
好吧,直接原样输出了。
ps : 由于用的少,我就直接抄官网的说明了。😊
Closure::call() 现在有着更好的性能,简短干练的暂时绑定一个方法到对象上闭包并调用它。
<?phpclass A {private $x = 1;}// php 7之前:$getXCB = function() {return $this->x;};$getX = $getXCB->bindTo(new A, 'A'); // intermediate closureecho $getX();// PHP 7:$getX = function() {return $this->x;};echo $getX->call(new A);
会输出:
1
1
unserialize 这个函数应该不陌生,它是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)}
现在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"
发现我目前为止并没用到,并没有什么乱用,好吧,继续下一个。
ps : 由于用的少,我就直接抄官网的说明了。😊
新增加的 IntlChar(http://php.net/manual/zh/class.intlchar.php) 类旨在暴露出更多的 ICU 功能。这个类自身定义了许多静态方法用于操作多字符集的 unicode 字符。
<?phpprintf('%x', IntlChar::CODEPOINT_MAX);echo IntlChar::charName('@');var_dump(IntlChar::ispunct('!'));
以上例程会输出:
10ffffCOMMERCIAL ATbool(true)
若要使用此类,请先安装Intl扩展
http://php.net/manual/zh/migration70.new-features.php
http://www.lanecn.com/article/main/aid-97
https://secure.php.net/manual/zh/migration70.incompatible.php