php5.3到php7.0.x新特性介绍

<?php
/*php5.3*/
echo '<hr>';
const MYTT = 'aaa';
#print_r(get_defined_constants());

/*
 5.4
新增短数组语法,比如 $a = [1, 2, 3, 4]; 或 $a = ['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4]; 。
新增支持对函数返回数组的成员访问解析,例如 foo()[0] 。
现在 闭包 支持 $this 。
现在不管是否设置 short_open_tag php.ini 选项,<?= 将总是可用。
新增在实例化时访问类成员,例如: (new Foo)->bar() 。
现在支持 Class::{expr}() 语法。
*/

echo '<pre>';
// php5.5
function xrange($start, $limit, $step = 1) {
    for ($i = $start; $i <= $limit; $i += $step) {
        yield $i;
    }
}

foreach (xrange(1, 9, 2) as $number) {
    echo "$number ";
}
echo '<hr>';

$array = [
    [1, 2],
    [3, 4],
];

foreach ($array as list($a, $b)) {
    echo "A: $a; B: $b<Br>";
}

echo '<hr>';
#empty() 支持任意表达式
function always_false() {
    return false;
}

if (empty(always_false())) {
    echo 'This will be printed.';
}

if (empty(true)) {
    echo 'This will not be printed.';
}
echo '<hr>';
echo 'String dereferencing: ';
echo 'PHP'[0];

echo '<hr>';

/*php5.6*/
#使用表达式定义常量
const ONE = 1;
const TWO = ONE * 2;

class C {
    const THREE = TWO + 1;
    const ONE_THIRD = ONE / self::THREE;
    const SENTENCE = 'The value of THREE is ' . self::THREE;

    public function f($a = ONE + self::THREE) {
        return $a;
    }
}

echo (new C)->f() . "<br>";
echo C::SENTENCE;

echo '<hr>';

#const 关键字来定义类型为 array 的常量
const MYARR = [1, 2];
print_r(MYARR);

echo '<hr>';

# 使用 ... 运算符定义变长参数函数   现在可以不依赖 func_get_args(), 使用 ... 运算符 来实现 变长参数函数。
function fun($arg1, $arg2 = null, ...$params) {
    //print_r(func_get_args());
    // $params 是一个包含了剩余参数的数组
    printf('$arg1:%d;$arg2:%d;总数为:%d<Br>', $arg1, $arg2, count($params));
}

fun(1);
fun(1, 2);
fun(1, 2, 3);
fun(1, 2, 3, 4);
fun(1, 2, 3, 4, 5);

echo '<hr>';

# 使用 ... 运算符进行参数展开  在调用函数的时候,使用 ... 运算符, 将 数组 和 可遍历 对象展开为函数参数
function add($a, $b, $c) {
    return $a + $b + $c;
}

$arr = [1, 2, 3];
echo add(...$arr);

echo '<hr>';
#使用 ** 进行幂运算
echo 2 ** 3;
echo '<hr>';

# use 运算符 被进行了扩展以支持在类中导入外部的函数和常量。 对应的结构为 use function 和 use const。
/*
namespace NameSpace {
    const FOO = 42;
    function f() { echo __FUNCTION__."
"; }
}

namespace {
    use const NameSpaceFOO;
    use function NameSpacef;

    echo FOO."
";
    f();
}
*/

# 使用 hash_equals() 比较字符串避免时序攻击
$expected  = crypt('12345', '$2a$07$usesomesillystringforsalt$');
$correct   = crypt('12345', '$2a$07$usesomesillystringforsalt$');
$incorrect = crypt('1234', '$2a$07$usesomesillystringforsalt$');

var_dump(hash_equals($expected, $correct));
var_dump(hash_equals($expected, $incorrect));
echo '<hr>';

# 加入 __debugInfo(), 当使用 var_dump() 输出对象的时候, 可以用来控制要输出的属性和值。
class Cc {
    private $prop;

    public function __construct($val) {
        $this->prop = $val;
    }

    public function __debugInfo() {
        return [
            'propSquared' => $this->prop ** 2,
        ];
    }
}

var_dump(new Cc(3));
echo '<hr>';

/*php7.0.x新特性*/
# 标量类型声明
/*
function sumOfInts(int ...$ints) {
    return array_sum($ints);
}

var_dump(sumOfInts(2, '3', 4.1));
// int(9)
echo '<hr>';
*/
# 返回值类型声明
/*
function arraysSum(array ...$arrays): array {
    return array_map(function (array $arr): int {
        return array_sum($arr);
    }, $arrays);
}
print_r(arraysSum([1,2,3], [4,5,6], [7,8,9]));
*/
/*
Array
(
    [0] => 6
    [1] => 15
    [2] => 24
)
*/
echo '<hr>';

# null合并运算符 由于日常使用中存在大量同时使用三元表达式和 isset()的情况, 我们添加了null合并运算符 (??) 这个语法糖。如果变量存在且值不为NULL, 它就会返回自身的值,否则返回它的第二个操作数。
/*
// $username = isset($_GET['user']) ? $_GET['user'] : 'nobody';
$username = $_GET['user'] ?? 'nobody';
echo $username;
// 先get和post如果两者都没有就用默认值
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
*/
echo '<hr>';

# 太空船操作符(组合比较符)
/*
// 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
*/

# 通过 define() 定义常量数组
/*
define('ANIMALS', [
    'dog',
    'cat',
    'bird'
]);
echo ANIMALS[1]; // outputs "cat"
*/

# 匿名类
/*
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());
*/

# Unicode codepoint 转译语法
// 这接受一个以16进制形式的 Unicode codepoint,并打印出一个双引号或heredoc包围的 UTF-8 编码格式的字符串。 可以接受任何有效的 codepoint,并且开头的 0 是可以省略的。
/*
echo "u{aa}";
echo "u{0000aa}";
echo "u{9999}";
以上例程会输出:
ª
ª (same as before but with optional leading 0's)
香
*/

# Closure::call() 现在有着更好的性能,简短干练的暂时绑定一个方法到对象上闭包并调用它。
class AA{
    private $x = 2;
}
/*
# php7之前的使用
$getXCB = function(){
    return $this->x;
};
$getx = $getXCB->bindTo(new AA,'AA');
echo $getx();
*/
/*
$getx = function(){
    return $this->x;
};
echo $getx->call(new AA);
*/

# 从同一 namespace 导入的类、函数和常量现在可以通过单个 use 语句 一次性导入了。
/*
// Pre PHP 7 code
use some
amespaceClassA;
use some
amespaceClassB;
use some
amespaceClassC as C;

use function some
amespacefn_a;
use function some
amespacefn_b;
use function some
amespacefn_c;

use const some
amespaceConstA;
use const some
amespaceConstB;
use const some
amespaceConstC;

// PHP 7+ code
use some
amespace{ClassA, ClassB, ClassC as C};
use function some
amespace{fn_a, fn_b, fn_c};
use const some
amespace{ConstA, ConstB, ConstC};
*/

# 生成器返回表达式 Generator Return Expressions
/*
$gen = (function() {
    yield 1;
    yield 2;

    return 3;
})();

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

echo $gen->getReturn(), PHP_EOL;
1
2
3
*/

# Generator delegation
/*
function gen()
{
    yield 1;
    yield 2;

    yield from gen2();
}

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

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

1
2
3
5
*/

# Integer division with intdiv()
/*
var_dump(intdiv(10, 3));
int(3)
*/
原文地址:https://www.cnblogs.com/ahwu/p/6184073.html