【modernPHP专题(1)】php7经常使用特性整理

PHP7性能

7最大的亮点,应该就是性能提升了两倍,某些测试环境下甚至提升到三到五倍,具体能够了解如下连接:php

PHP7 VS HHVM (WordPress)html

HHVM vs PHP 7 – The Competition Gets Closer! 数组

PHP 7.0 Is Showing Very Promising Performance Over PHP 5, Closing Gap With HHVM安全

PHP7革新与性能优化性能优化

经常使用特性整理

标量类型声明

PHP 7 中的函数的形参类型声明能够是标量了。在 PHP 5 中只能是类名、接口、array 或者 callable (PHP 5.4,便可以是函数,包括匿名函数),如今也可使用 string、int、float和 bool 了php7

<?php

// 强制模式,强制把参数int化
function sumOfInts(int ...$ints)
{
    return array_sum($ints);
}

var_dump(sumOfInts(2, '3', 4.1));
强制模式(默认,既强制类型转换)下会对不符合预期的参数进行强制类型转换,但严格模式下则触发 TypeError 的致命错误。
严格模式:申明 declare(strict_types=1)便可;

返回值类型声明

PHP 7 增长了对返回类型声明的支持。 相似于参数类型声明,返回类型声明指明了函数返回值的类型。可用的类型与参数声明中可用的类型相同。闭包

function arraysSum(array ...$arrays): array
{
   # 把返回值强制转换为string
    return array_map(function(array $array): string {
        return array_sum($array);
    }, $arrays);
}

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

# output
array(3) {
  [0]=>
  string(1) "6"
  [1]=>
  string(2) "15"
  [2]=>
  string(2) "24"
}

// 7.1 要么string,要么是null
function testReturn(): ?string
{
    return null;
}

// 7.1 要么没有return,要么使用空的return。
// 对于 void来讲,NULL 不是一个合法的返回值。虽然它返回的也是个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);

// 7.1 返回对象类型
function test(object $obj) : object
{
    return new SplQueue();
}

// 7.1
// iterable: 数组或者实现Traversable接口的对象
// Traversable也就是 IteratorAggregate 或 Iterator 接口实现。
// 也就是函数必需要传入一个可foreach遍历的参数,以及返回一个可foreach遍历的值
function iterator(iterable $iter) : iterable
{
    foreach ($iter as $val) {
        //
    }
}
一样有严格模式和强制模式

容许重写抽象方法(Abstract method)

abstract class A
{
    abstract function test(string $s);
}
abstract class B extends A
{
    // 当一个抽象类继承于另一个抽象类的时候,继承后的抽象类能够重写被继承的抽象类的抽象方法。
    abstract function test($s) : int;
}

运算符...

5.6就有此特性了,但在PHP7的的程序代码中才发现大量使用app

使用...运算符定义变长参数函数异步

function f($req, $opt = null, ...$params) {
    // $params 是一个包含了剩余参数的数组
    printf('$req: %d; $opt: %d; number of params: %d'."\n",
           $req, $opt, count($params));
}

f(1);
f(1, 2);
f(1, 2, 3);
f(1, 2, 3, 4);

# output
$req: 1; $opt: 0; number of params: 0
$req: 1; $opt: 2; number of params: 0
$req: 1; $opt: 2; number of params: 1
$req: 1; $opt: 2; number of params: 2

使用...运算符进行参数展开async

function add($a, $b, $c) {
    return $a + $b + $c;
}

$operators = [2, 3];
echo add(1, ...$operators); // output: 6

NULL 合并运算符

// 若是 $_GET['user'] 不存在返回 'nobody',不然返回 $_GET['user'] 的值
$username = $_GET['user'] ?? 'nobody';

// 至关于
isset($_GET['user']) ?  $_GET['user'] : 'nobody';

// 相似于屏蔽notice错误后的:
$username = $_GET['user'] ?: 'nobody';

太空船操做符(组合比较符)

用于比较两个表达式。当$a大于、等于或小于$b时它分别返回-一、0或1。

<?php
// $a 是否大于 $b , 大于就返回1
// 整型
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1

// 浮点型
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1

// 字符串
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1

经过 define() 定义常量数组

<?php

define('ANIMALS', [
    'dog',
    'cat',
    'bird'
]);

// ANIMALS[1] = mouse; 常量数组里面的值,是不能够更改的

echo ANIMALS[1]; // 输出 "cat"

匿名类

如今支持经过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());

# output:
object(class@anonymous)#2 (0) {
}

为unserialize()提供过滤

这个特性旨在提供更安全的方式解包不可靠的数据。它经过白名单的方式来防止潜在的代码注入。

// 转换对象为 __PHP_Incomplete_Class 对象
$data = unserialize($foo, ["allowed_classes" => false]);

// 转换对象为 __PHP_Incomplete_Class 对象,除了 MyClass 和 MyClass2
$data = unserialize($foo, ["allowed_classes" => ["MyClass", "MyClass2"]]);

// 默认接受全部类
$data = unserialize($foo, ["allowed_classes" => true]);

断言assert

向后兼用并加强以前的 assert() 的方法。 它使得在生产环境中启用断言为零成本,而且提供当断言失败时抛出特定异常的能力。

ini_set('assert.exception', 1);

class CustomError extends AssertionError {}
assert(2 == 1, new CustomError('Some error message'));

use 增强

从同一 namespace 导入的类、函数和常量如今能够经过单个 use 语句 一次性导入了。

//  PHP 7 以前版本用法
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;

// PHP 7+ 用法
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};

Generator 增强 : yield from

加强了Generator的功能,这个能够实现不少先进的特性

function gen()
{
    yield 1;
    yield 2;

    yield from gen2();
}

function gen2()
{
    yield 3;
    yield 4;
}

foreach (gen() as $val)
{
    echo $val, PHP_EOL;
}

整除

新增了整除函数 intdiv()

var_dump(intdiv(10, 3)); # 3

array_column() 和 list()

新增支持对象数组

list($a, $b) = (object) new ArrayObject([0, 1]);
// PHP7结果:$a == 0 and $b == 1.
// PHP5结果:$a == null and $b == null.

// 短数组语法([])如今做为list()语法的一个备选项
$data = [
    [1, 'Tom'],
    [2, 'Fred'],
];

// list() style
list($id1, $name1) = $data[0];

// [] style
[$id1, $name1] = $data[0]; # $id1 : 1

// 7.1还支持键名
["id" => $id1, "name" => $name1] = $data[0];

dirname()

增长了可选项$levels,能够用来指定目录的层级。dirname(dirname($foo)) => dirname($foo, 2);

Closure::call()

Closure::call() 如今有着更好的性能,简短干练的暂时绑定一个方法到对象上闭包并调用它。

class A {private $x = 1;}

// Pre PHP 7 代码
$getXCB = function() {return $this->x;};
$getX = $getXCB->bindTo(new A, 'A'); 
echo $getX();

//// PHP 7+ 代码
$getX = function() {return $this->x;};
echo $getX->call(new A);

类常量可见性

支持设置类常量的可见性。

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

错误和异常

PHP 7 改变了大多数错误的报告方式。不一样于传统(PHP 5)的错误报告机制,如今大多数错误被做为Error异常抛出。

// 7.1 多异常捕获
try {
    // some code
} catch (FirstException | SecondException $e) {
    // handle first and second exceptions
}

try
{
    throw new Error('message');
//    throw new Exception('message');
}
// 捕获全部的异常和错误
catch (Throwable $t)
{
    echo 'Throwable: ' . $t->getMessage();
}
// 只捕获错误
catch (Error $e)
{
    echo 'Error : ' . $e->getMessage();
}
// 只捕获异常
catch (Exception $e)
{
    echo 'Exception : ' . $e->getMessage();
}

异步信号处理

//开启异步信号处理
pcntl_async_signals(true);

// SIGINT信号也就是ctrl+c,当ctrl+c的时候触发此回调
pcntl_signal(SIGINT, function(){
    echo '捕获到SIGINT信号' . PHP_EOL;
});

$i = 0;
while(1)
{
    echo $i++ . PHP_EOL;
    sleep(1);
}

更多请参考:

关于PHP7新特性

相关文章
相关标签/搜索