This article mainly introduces the new characteristics of the PHP7, here the detailed information and simple implementation code to help you learn to reference the new features of knowledge, interested friends can refer to the next
New features of PHP learning
Recent projects have used PHP7, but feel that there are many new features that are not used. Just want to summarize some of the new features that might be used. The previously used environment is php5.4, and all of the features of php5.5 and php5.6 are summarized here, listing only the features I think might be used in the project, mainly from the appendix of the PHP Manual.
Generators (PHP 5 >= 5.5.0, PHP 7)
By adding the yield keyword, generators,generators provides an easier way to implement iterators without implementing the Iterator interface.
<?phpfunction xrange ($start, $limit, $step = 1) {for ($i = $start; $i <= $limit; $i + = $step) { yield $i;}} echo ' single digit odd numbers: ';/* Note An array that is stored in memory will never be created or returned */foreach (xrange (1, 9, 2) as $number) {echo "$number";}
The above routines will output:
Single digit odd numbers:1 3 5 7 9
Click the Builder for details
New finally keyword (PHP 5 >= 5.5.0, PHP 7)
Try-catch now supports finally
foreach now supports list () (PHP 5 >= 5.5.0, PHP 7)
The foreach control structure now supports separating nested arrays into separate variables through the list () construct. For example:
<?php$array = [[1, 2], [3, 4],];foreach ($array as List ($a, $b)) {echo "A: $a; B: $b \ n ";}? >
The above routines will output:
a:1; B:2
A:3; B:4
Array_column (PHP 5 >= 5.5.0, PHP 7)
array_column-returns a column specified in the array
Defining constants Using Expressions (PHP 5 >= 5.6.0, PHP 7)
In previous versions of PHP, 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 numeric values, string literals, and other constants, to define constants, declare properties, and set default values for function parameters.
<?phpconst one = 1;const, one * 2;class C {const THREE = 1; const ONE_THIRD = one/self::three; Const SENT ENCE = ' The value of three is '. Self::three; Public function f ($a = one + Self::three) { return $a;}} Echo (New C)->f (). " \ n "; Echo c::sentence;? >
The above routines will output:
4
The value of three is 3
Constants of type array can now be defined with the Const keyword.
<?phpconst ARR = [' A ', ' B '];echo arr[0];? >
The above routines will output:
A
Use... Operators define variable-length parametric functions (PHP 5 >= 5.6.0, PHP 7)
Now you can not rely on Func_get_args (), using ... operator to implement variable-length parametric functions.
<?phpfunction f ($req, $opt = null, ... $params) {//$params is an array containing the remaining parameters printf (' $req:%d; $opt:%d; number of the params: %d '. " \ n ", $req, $opt, Count ($params));} f (1); F (1, 2); F (1, 2, 3); F (1, 2, 3, 4); F (1, 2, 3, 4, 5);? >
The above routines 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
$req: 1; $opt: 2; Number of Params:3
Use... Operator for parameter expansion (PHP 5 >= 5.6.0, PHP 7)
When calling a function, use the ... operator to expand the array and the traversed object to function parameters. In other programming languages, such as Ruby, this is called the join operator.
<?phpfunction Add ($a, $b, $c) {return $a + $b + $c;} $operators = [2, 3];echo Add (1, ... $operators);? >
The above routines will output:
6
Use function and use const (PHP 5 >= 5.6.0, PHP 7)
The use operator is extended to support the import of external functions and constants in a class. The corresponding structure is the use function and the use Const.
<?phpnamespace name\space {Const FOO = A, function f () {echo function. \ n "; }}namespace {Use const Name\space\foo; use function name\space\f; echo FOO. " \ n "; f ();}? >
The above routines will output:
42
Name\space\f
Debuginfo () (PHP 5 >= 5.6.0, PHP 7)
adding Debuginfo (), when using the Var_dump () output object, can be used to control the properties and values to be output.
<?phpclass C {private $prop; public function construct ($val) { $this->prop = $val;} Public Function Debuginfo ( { return [ ' propsquared ' = ' $this->prop * * 2, ];} Var_dump (New C (42));? >
The above routines will output:
Object (C) #1 (1) {["propsquared"]=> int (1764)}
Scalar type declaration (PHP 7)
Scalar type declarations have two modes: mandatory (default) and strict mode. You can now use the following type parameters, whether in forced or strict mode: string (String), Integer (int), floating-point number (float), and Boolean (bool). They augment the other types introduced in PHP5: Class name, interface, array, and callback type.
<?php//coercive modefunction sumofints (int ... $ints) {return array_sum ($ints);} Var_dump (sumofints (2, ' 3 ', 4.1));
The above routines will output:
Int (9)
To use strict mode, a declare declaration directive must be placed at the top of the file. This means that the scalar is strictly declared to be file-based. This directive affects not only the type declaration of the parameter, but also the return value declaration of the function (see return value type declaration, built-in PHP functions, and PHP functions loaded in the extension)
return value type declaration (PHP 7)
PHP 7 adds support for return type declarations. Similar to a parameter type declaration, the return type declaration indicates the type of the function return value. The available types are the same as the types available in the parameter declaration.
<?phpfunction arrayssum (Array ... $arrays): array{return Array_map (function (array $array): int { return Array_ SUM ($array); }, $arrays);} Print_r ([Arrayssum], [4,5,6], [7,8,9]);
The above routines will output:
Array
(
[0] = 6
[1] = 15
[2] = 24
)
Null merge operator (PHP 7)
Because of the large number of simultaneous use of ternary expressions and isset () in daily use, we added the syntax sugar of the null merge operator (??). If a variable exists and the value 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 was equivalent to: $username = isset ($_get[' user ')? $_get[' user ': ' nobody ';//coalesces can be chained:this would return the first//defined value out of $_get[' user '], $_p ost[' user ', and//' nobody '. $username = $_get[' user ']?? $_post[' user '?? ' Nobody ';? >
Spaceship operator (combination comparator) (PHP 7)
The spaceship operator is used to compare two expressions. When $ A is less than, equal to, or greater than $b, it returns-1, 0, or 1, respectively. The principle of comparison is to follow the regular comparison rules of PHP.
<?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?>
Defining a constant array by define () (PHP 7)
Constants of type Array can now be defined by define (). can only be defined by const in PHP5.6.
<?phpdefine (' ANIMALS ', [' dog ', ' cat ', ' bird '), Echo animals[1]; Outputs "Cat"?>
Anonymous class (PHP 7)
It is now supported to instantiate an anonymous class with the new class, which can be used instead of some full-burn class definitions.
<?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 ());? >
The above routines will output:
Object (class@anonymous) #2 (0) {
}
Closure::call () (PHP 7)
Closure::call () now has better performance, a short, skilful way to temporarily bind a method to a closure on an object and invoke it.
<?phpclass A {Private $x = 1;} Pre PHP 7 CODE$GETXCB = function () {return $this->x;}; $getX = $getXCB->bindto (new A, ' a '); Intermediate Closureecho $getX ();//PHP 7+ code$getx = function () {return $this->x;}; Echo $getX->call (new A);
The above routines will output:
1
1
Provides filtering for Unserialize () (PHP 7)
This feature is designed to provide a more secure way of unpacking unreliable data. It prevents potential code injection by using a whitelist approach.
<?php//converts all objects into php_incomplete_class object$data = Unserialize ($foo, ["allowed_classes" = false] );//converts all objects into Php_incomplete_class object except those of MyClass and Myclass2$data = Unserialize ($foo, [ "Allowed_classes" = ["MyClass", "MyClass2"]);//default behaviour (same as omitting the second argument) that accepts All Classes$data = Unserialize ($foo, ["allowed_classes" = true]);
Group Use declarations (PHP 7)
Classes, functions, and constants imported from the same namespace can now be imported once with a single use statement.
<?php//pre PHP 7 codeuse 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+ Codeuse Some\namespace\{classa, ClassB, ClassC as C};use function some\namespace\{fn_a, Fn_b, Fn_c};use const SOME\NAME Space\{consta, Constb, CONSTC};?