A detailed introduction to the new features of PHP 7 and a detailed introduction to the new features of PHP 7

Source: Internet
Author: User

A detailed introduction to the new features of PHP 7 and a detailed introduction to the new features of PHP 7

New Features of PHP Learning

Recently, PHP 7 is used for the project, but many new features are useless. I would like to summarize some new features that may be used. The environment used previously was php5.4, and all the features of php5.5 and php5.6 will be summarized. Here we only list the features that I think may be used in the project. The main content is from the appendix of the php manual.

Generators (PHP 5> = 5.5.0, PHP 7)

Generators is supported by adding the yield keyword. Generators provides a simpler method to implement the Iterator 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 that arrays stored in the memory will never be created or returned */foreach (xrange (1, 9, 2) as $ number) {echo "$ number ";}

The above routine will output:

Single digit odd numbers: 1 3 5 7 9

Click Generator for details

Added the 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 by using the list () structure. For example:

<?php$array = [ [1, 2], [3, 4],];foreach ($array as list($a, $b)) { echo "A: $a; B: $b\n";}?>

The above routine will output:

A: 1; B: 2
A: 3; B: 4

Array_column (PHP 5> = 5.5.0, PHP 7)

Array_column-returns a specified column in the array.

Use expressions to define constants (PHP 5> = 5.6.0, PHP 7)

In the previous PHP version, static values must be used to define constants, declare attributes, and specify the default values of function parameters. Now you can use numeric expressions including numeric values, string literal values, and other constants to define constants, declare attributes, and set default values of function parameters.

<?phpconst 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()."\n";echo C::SENTENCE;?>

The above routine will output:

4

The value of THREE is 3

Now we can use the const keyword to define constants of the array type.

<?phpconst ARR = ['a', 'b'];echo ARR[0];?>

The above routine will output:

A

Use the... operator to define the Variable Length Parameter Function (PHP 5> = 5.6.0, PHP 7)

Currently, variable-length parameter functions can be implemented using the... operator without relying on func_get_args.

<? Phpfunction f ($ req, $ opt = null ,... $ params) {// $ params is an array 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); f (1, 2, 3, 4, 5);?>

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
$ Req: 1; $ opt: 2; number of params: 3

Use the... operator to expand parameters (PHP 5> = 5.6.0, PHP 7)

When calling a function, use the... operator to expand the array and traversal objects as function parameters. In other programming languages, such as Ruby, this is called a concatenation operator ,.

<?phpfunction add($a, $b, $c) { return $a + $b + $c;}$operators = [2, 3];echo add(1, ...$operators);?>

The above routine will output:

6

Use function and use const (PHP 5> = 5.6.0, PHP 7)

The use operator is extended to support importing external functions and constants into the class. The corresponding structure is use function and use const.

<?phpnamespace 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

_ DebugInfo () (PHP 5> = 5.6.0, PHP 7)

Add _ debugInfo () to control the attributes and values to be output when var_dump () is used to output an object.

<?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 routine will output:

object(C)#1 (1) { ["propSquared"]=> int(1764)}

Scalar type declaration (PHP 7)

Scalar type declaration has two modes: forced (default) and strict mode. You can now use the following types of parameters (either in forced mode or in strict mode): string, INTEGER (int), floating point number (float), and Boolean value (bool ). They expand other types introduced in PHP5: Class names, interfaces, arrays, and callback types.

<?php// Coercive modefunction sumOfInts(int ...$ints){ return array_sum($ints);}var_dump(sumOfInts(2, '3', 4.1));

The above routine will output:

Int (9)

To use the strict mode, a declare declaration command must be placed at the top of the file. This means that the scalar is strictly declared to be file-configurable. This command affects not only the parameter type declaration, but also the function return value declaration (see the return value type declaration, built-in PHP functions, and the PHP functions loaded in the extension)

Return Value Type Declaration (PHP 7)

PHP 7 adds support for the return type declaration. Similar to the parameter type declaration, the return type declaration specifies the type of the function return value. The available types are the same as those 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([1,2,3], [4,5,6], [7,8,9]));

The above routine will output:

Array
(
[0] => 6
[1] => 15
[2] => 24
)

Null merge operator (PHP 7)

Because a large number of ternary expressions and isset () are used in daily use, we have added the null merge operator (??) This syntactic sugar. If the 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 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';?>

Space Ship Operator (composite operator) (PHP 7)

The spacecraft operator is used to compare two expressions. If $ a is less than, equal to, or greater than $ B, it returns-1, 0, or 1. The comparison principle is based on the conventional 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?>

Use define () to define a constant array (PHP 7)

Constants of the Array type can now be defined by define. PHP5.6 can only be defined by const.

<?phpdefine('ANIMALS', [ 'dog', 'cat', 'bird']);echo ANIMALS[1]; // outputs "cat"?>

Anonymous class (PHP 7)

Currently, an anonymous class can be instantiated using the new class, which can be used to replace some complete class definitions that are "immediately burned.

<?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 routine will output:

Object (class @ anonymous) #2 (0 ){
}

Closure: call () (PHP 7)

Closure: call () now has better performance. It is short and competent to temporarily bind a method to the Closure of the object and call 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 routine will output:

1
1

Provide Filtering for unserialize () (PHP 7)

This feature aims to provide a safer way to unpackage unreliable data. It uses a whitelist to prevent potential code injection.

<?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 at one time using 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\namespace\{ConstA, ConstB, ConstC};?>

Summary: The content is all from the php documentation. The new features skipped here will be added later ~~

The above is to sort out the new features of PHP, and continue to add relevant information in the future. Thank you for your support for this site!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.