Home > Article > Backend Development > Organize new features of PHP5.5 ~ PHP7.2
PHP5.5 ~ PHP7.2 new features arrangement
1. Migrating from PHP 5.5.x to PHP 5.6.x
In previous PHP versions, you had to use static values to define constants, declare properties, and specify default values for function parameters. You can now use numeric expressions including numbers, string literals, and other constants to define constants, declare properties, and set default values for function parameters.
<?php 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; }
You can now define constants of type array through the const keyword.
<?php const ARR = ['a', 'b']; echo ARR[0];
...
operator to define a variable-length parameter functionYou can now use the... operator without relying on func_get_args() To implement a variable-length parameter function.
<?php 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); ?>
The above routine will 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
...
operator for parameter expansionWhen calling the function When using... operator, arrays and traversable objects are expanded into function parameters. In other programming languages, such as Ruby, this is called the concatenation operator.
<?php function add($a, $b, $c) { return $a + $b + $c; } $operators = [2, 3]; echo add(1, ...$operators); ?>
The above routine will output:
6
use operators have been extended to support importing in classes External functions and constants. The corresponding structures are use function and use const.
<?php namespace Name\Space { const FOO = 42; function f() { echo __FUNCTION__."\n"; } } namespace { use const Name\Space\FOO; use function Name\Space\f; echo FOO."\n"; f(); } ?>
The above routine will output:
42 Name\Space\f
Recommended (free): PHP7
##2. Migrating from PHP 5.6.x to PHP 7.0.x
<?php // Coercive mode function sumOfInts(int ...$ints) { return array_sum($ints); } var_dump(sumOfInts(2, '3', 4.1));The above routine will output:
int(9)
<?php function arraysSum(array ...$arrays): array { return array_map(function(array $array): int { return array_sum($array); }, $arrays); }
??) This syntactic sugar. If the variable exists and is not NULL, it returns its own value, otherwise it returns its second operand.
<?php // Fetches the value of $_GET['user'] and returns 'nobody' if it does not exist. $username = $_GET['user'] ?? 'nobody'; // This is equivalent to: $username = isset($_GET['user']) ? $_GET['user'] : 'nobody'; // Coalesces can be chained: this will return the first defined value out of $_GET['user'], $_POST['user'], and 'nobody'. $username = $_GET['user'] ?? $_POST['user'] ?? 'nobody'; ?>
<?php // 整数 echo 1 <=> '1'; // 0 echo 1 <=> 2; // -1 echo 2 <=> 1; // 1 // 浮点数 echo '1.50' <=> 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('ANIMALS', [ 'dog', 'cat', 'bird' ]); echo ANIMALS[1]; // 输出 "cat"
<?php class A {private $x = 1;} // 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);The above routine will output:
1
Statement
<?php // 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}; ?>
Ported from PHP 7.0.x to PHP 7.1.x
<?php function testReturn(): ?string { return 'elePHPant'; } var_dump(testReturn()); function testReturn(): ?string { return null; } var_dump(testReturn()); function test(?string $name) { var_dump($name); } test('elePHPant'); test(null); test();The above routine will output:
string(10) "elePHPant" NULL string(10) "elePHPant" NULL Uncaught Error: Too few arguments to function test(), 0 passed in...
<?php 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);The above routine will output:
null int(2) int(1)
<?php $data = [ [1, 'Tom'], [2, 'Fred'], ]; // list() style list($id1, $name1) = $data[0]; // [] style [$id1, $name1] = $data[0]; // list() style foreach ($data as list($id, $name)) { // logic here with $id and $name } // [] style foreach ($data as [$id, $name]) { // logic here with $id and $name }
<?php class ConstDemo { const PUBLIC_CONST_A = 1; public const PUBLIC_CONST_B = 2; protected const PROTECTED_CONST = 3; private const PRIVATE_CONST = 4; }
现在引入了一个新的被称为iterable的伪类 (与callable类似)。 这可以被用在参数或者返回值类型中,它代表接受数组或者实现了Traversable接口的对象。 至于子类,当用作参数时,子类可以收紧父类的iterable类型到array 或一个实现了Traversable的对象。对于返回值,子类可以拓宽父类的 array或对象返回值类型到iterable。
<?php function iterator(iterable $iter) : iterable { foreach ($iter as $val) { // } }
一个catch语句块现在可以通过管道字符(|)来实现多个异常的捕获。 这对于需要同时处理来自不同类的不同异常时很有用。
<?php try { // some code } catch (FirstException | SecondException $e) { // handle first and second exceptions }
list()
现在支持键名现在list()和它的新的[]语法支持在它内部去指定键名。这意味着它可以将任意类型的数组 都赋值给一些变量(与短数组语法类似)
<?php $data = [ ["id" => 1, "name" => 'Tom'], ["id" => 2, "name" => 'Fred'], ]; // list() style list("id" => $id1, "name" => $name1) = $data[0]; // [] style ["id" => $id1, "name" => $name1] = $data[0]; // list() style foreach ($data as list("id" => $id, "name" => $name)) { // logic here with $id and $name } // [] style foreach ($data as ["id" => $id, "name" => $name]) { // logic here with $id and $name }
从PHP 7.1.x 移植到 PHP 7.2.x
这种新的对象类型, object, 引进了可用于逆变(contravariant)参数输入和协变(covariant)返回任何对象类型。
<?php function test(object $obj) : object { return new SplQueue(); } test(new StdClass());
当一个抽象类继承于另外一个抽象类的时候,继承后的抽象类可以重写被继承的抽象类的抽象方法。
abstract class A { abstract function test(string $s); } abstract class B extends A { // overridden - still maintaining contravariance for parameters and covariance for return abstract function test($s) : int; }
重写方法和接口实现的参数类型现在可以省略了。不过这仍然是符合LSP,因为现在这种参数类型是逆变的。
interface A { public function Test(array $input); } class B implements A { public function Test($input){} // type omitted for $input }
命名空间可以在PHP 7中使用尾随逗号进行分组引入。
use Foo\Bar\{ Foo, Bar, Baz, };
The above is the detailed content of Organize new features of PHP5.5 ~ PHP7.2. For more information, please follow other related articles on the PHP Chinese website!