PHP7新特性
Generator syntax 新方法实现迭代
function gen_one_to_three() {
for ($i = 1; $i <= 3; $i++) {
// Note that $i is preserved between yields.
yield $i;
}
}
$generator = gen_one_to_three();
foreach ($generator as $value) {
echo "$value\n";
}
Yielding values with keys
$input = <<<'EOF'
1;PHP;Likes dollar signs
2;Python;Likes whitespace
3;Ruby;Likes blocks
EOF;
function input_parser($input) {
foreach (explode("\n", $input) as $line) {
$fields = explode(';', $line);
$id = array_shift($fields);
yield $id => $fields;
}
}
foreach (input_parser($input) as $id => $fields) {
echo "$id:\n";
echo " $fields[0]\n";
echo " $fields[1]\n";
}
Constants
const ANIMALS = array('dog', 'cat', 'bird');
echo ANIMALS[1]; // outputs "cat"
// Works as of PHP 7
define('ANIMALS', [
'dog',
'cat',
'bird'
]);
echo ANIMALS[1]; // outputs "cat"
返回值类型声明
function hello() : array
{
return [];
}
NULL 合并运算符 (免去三元表达式的繁琐)
$username = $_GET['username'] ?? null;
// 等价于
$username = isset($_GET['username']) ? $_GET['username'] : null;
//注意,下面的写法是错误的, $username 的值变成true/false 了。
$username = isset($_GET['username']) ?? null;
通过 define() 定义常量数组
define('ANIMALS', [
'dog',
'cat',
'bird'
]);
整除
var_dump(intdiv(10, 3)); => 3
PHP7.1 特性
https://secure.php.net/manual/en/migration71.new-features.php
Nullable types
function testReturn(): ?string
{
return 'elePHPant';
}
Void functions
function swap(&$left, &$right): void
{
if ($left === $right) {
return;
}
$tmp = $left;
$left = $right;
$right = $tmp;
}