A summary of the new grammatical features in PHP7.0 and php7.1

Source: Internet
Author: User
Tags intl iterable
This article brings to you the content is about PHP7.0 and php7.1 in the grammar of the new features of the summary, there is a certain reference value, the need for friends can refer to, I hope to help you.

New features of php7.0:

1. Empty merge operator (??). )

Simplified judgment

$param = $_get[' param '?? 1;

Equivalent:

$param = isset ($_get[' param ')? $_get[' param ': 1;

2. Variable type declaration

Two modes: Mandatory (default) and strict mode
Type: string, int, float, and bool

function add (int $a) {     return 1+ $a;} var_dump (Add (2);

3. Return value type declaration

Both the function and the anonymous function can specify the type of the return value

Function Show (): array {     return [1,2,3,4];} function Arrayssum (array ... $arrays): array {return Array_map (function (array $array): int {return array_sum ($array);}, $ arrays);}

4. Spaceship operator (combination comparator)

The spaceship operator is used to compare two expressions. When a is greater than, equal to, or less than B, it returns-1, 0, or 1, respectively. The principle of comparison is to follow the regular comparison rules of 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

5. Anonymous class

It is now supported to instantiate an anonymous class with the new class, which can be used instead of some full-burn class definitions.

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 $m (SG;    }}); Var_dump ($app->getlogger ());

6. Unicode codepoint Translation Syntax

This accepts a Unicode codepoint in the form of 16, and prints a string in a double-quote or heredoc-enclosed UTF-8 encoded format. Any valid codepoint can be accepted, and 0 of the beginning can be omitted.

echo "\u{9876}"

Legacy output: \u{9876}
New input: Top

7, Closure::call ()

Closure::call () now has better performance, a short, skilful way to temporarily bind a method to a closure on an object and invoke it.

Class Test {public    $name = "Lixuan";} Both PHP7 and PHP5.6 can $getnamefunc = function () {    return $this->name;}; $name = $getNameFunc->bindto (new test, ' test '), Echo $name (),//php7 Yes, PHP5.6 error $getx = function () {    return $this-& Gt;name;}; Echo $getX->call (new Test);

8. Provide filtering for unserialize ()

This feature is designed to provide a more secure way of unpacking unreliable data. It prevents potential code injection by using a whitelist approach.

Divide all objects into __php_incomplete_class objects $data = unserialize ($foo, ["allowed_classes" = false]);//Divide all objects into __php_ Incomplete_class objects except ClassName1 and Classname2$data = Unserialize ($foo, ["allowed_classes" + = ["ClassName1", " ClassName2 "]);//default behavior, same as Unserialize ($foo) $data = Unserialize ($foo, [" allowed_classes "= true]);

9, Intlchar

The newly added Intlchar class is designed to expose more ICU functionality. This class itself defines a number of static methods used to manipulate Unicode characters for multiple character sets. Intl is a pecl extension that needs to be compiled into PHP before use, or Apt-get/yum/port install Php5-intl

printf ('%x ', Intlchar::codepoint_max); Echo intlchar::charname (' @ '); Var_dump (intlchar::ispunct ('! '));

The above routines will output:
10ffff
Commercial at
BOOL (TRUE)

10. Expected

It is expected that the previous assert () method is used backwards and strengthened. It enables the assertion to be zero-cost in a production environment, and provides the ability to throw specific exceptions when an assertion fails. The old version of the API will continue to be maintained for compatibility purposes, and assert () is now a language structure that allows the first argument to be an expression, not just a string to be computed or a Boolean to be tested.

Ini_set (' assert.exception ', 1); class Customerror extends Assertionerror {}assert (False, New Customerror (' Some error Message '));

The above routines will output:
Fatal error:uncaught customerror:some Error message

11. Group Use Declarations

Classes, functions, and constants imported from the same namespace can now be imported once with a single use statement.

PHP7 before 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;//PHP7 after 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};

12, INTP ()

Receives two parameters as dividend and divisor, returning the integer portion of the result of their division.

Var_dump (INTP (7, 2));

Output int (3)

13, Csprng

Two new functions: Random_bytes () and Random_int (). You can encrypt the production of protected integers and strings. Anyway, the random number becomes safe.
random_bytes-encryption survival protected pseudo-random string
random_int-encryption survival protected pseudo-random integer

14, Preg_replace_callback_array ()

A new function, Preg_replace_callback_array (), is used to make the code more elegant when using the Preg_replace_callback () function. Before PHP7, the callback function invokes each regular expression, and the callback function is contaminated on some branches.

15. Session Options

Now, the session_start () function can receive an array as an argument, overwriting the configuration of the session in PHP.ini.
For example, set the Cache_limiter to private and close immediately after reading the session.

Session_Start ([' cache_limiter ' = ' private ',               ' read_and_close ' = true,]);

16, the Generator return value

The concept of introducing generators in PHP5.5. The generator function gets a yield ID value each time it executes. In PHP7, when the generator iteration is complete, you can get the return value of the generator function. obtained by Generator::getreturn ().

function Generator () {    yield 1;    Yield 2;    Yield 3;    Return "a";} $generatorClass = ("generator") (), foreach ($generatorClass as $val) {    echo $val. ";} echo $generatorClass->getreturn ();

Output is: 1 2 3 A

17. Introducing other generators into the generator

You can introduce another or several generators in the generator, just write yield from functionName1

function Generator1 () {    yield 1;    Yield 2;    Yield from Generator2 ();    Yield from Generator3 ();} function Generator2 () {    yield 3;    Yield 4;} function Generator3 () {    yield 5;    Yield 6;} foreach (Generator1 () as $val) {    echo $val, "";}

Output: 1 2 3 4 5 6

18. Define a constant array by define ()

Define (' ANIMALS ', [' dog ', ' cat ', ' bird '), Echo animals[1]; Outputs "Cat"

New features of php7.1:

1, Nullable (Nullable) type

The type is now allowed to be empty, and when this feature is enabled, the passed parameter or function returns either the given type or null. You can make it nullable by adding a question mark before the type.

function Test (? string $name) {    var_dump ($name);}

The above routines will output:

String (5) "Tpunt" nulluncaught error:too few arguments to function test (), 0 passed in ...

2. Void function

On the basis of the other return value types introduced in PHP 7, a new return value type void is introduced. A method that declares a value of type void either simply omits the return statement or uses an empty return statement. For void functions, NULL is not a valid return value.

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 routines will output:

Nullint (2) int (1)

Attempting to get the return value of a void method will result in null, and no warning will be generated. The reason for doing this is not wanting to influence a higher-level approach.

3. Short array Syntax symmetric array destructuring

The short array Syntax ([]) can now be used to assign the value of an array to some variables (including in foreach). This approach makes it easier to extract values from the array.

$data = [    [' id ' = = 1, ' name ' = ' Tom '],    [' id ' = + 2, ' name ' = ' Fred '],];while ([' id ' = ' + ') ', ' name ' = = $name] = $data) {    //logic here with $id and $name}

4. Class constant visibility

It is now supported to set the visibility of class constants.

Class constdemo{    Const PUBLIC_CONST_A = 1;    Public Const PUBLIC_CONST_B = 2;    protected const PROTECTED_CONST = 3;    Private Const PRIVATE_CONST = 4;}

5, iterable pseudo-class

A new pseudo-class called iterable (similar to callable) is now introduced. This can be used in a parameter or return value type, which represents an object that accepts an array or implements a traversable interface. As for subclasses, subclasses can tighten the iterable type of the parent class to an array or an object that implements traversable when used as a parameter. For return values, subclasses can widen the parent class's array or object return value type to iterable.

Function iterator (iterable $iter) {    foreach ($iter as $val) {        //    }}

6, multi-exception capture processing

A catch statement block can now be passed through the pipe character (|) To implement the capture of multiple exceptions. This is useful when you need to handle different exceptions from different classes at the same time.

try {    //Some code} catch (Firstexception | Secondexception $e) {    //handle First and second exceptions} catch (\exception $e) {    //...}

7. List () now supports key names

The list () now supports specifying the key name inside it. This means that it can assign any type of array to some variable (similar to a short array syntax)

$data = [    [' id ' = = 1, ' name ' = ' Tom '],    [' id ' = + 2, ' name ' = ' Fred '],];while (list (' id ' = ' + $id, ' n Ame ' = $name) = $data) {    //logic here with $id and $name}

8, support for negative string offset

Now all the built-in string-based functions with offset are supported to accept negative numbers as offsets, including the array dereference operator ([]).

Var_dump ("abcdef" [-2]); Var_dump (Strpos ("AABBCC", "B",-3));

The above routines will output:

String (1) "E" int (3)

9, EXT/OPENSSL support Aead

By adding additional parameters to Openssl_encrypt () and Openssl_decrypt (), the Aead (mode GCM and CCM) is now supported.
Turn Callables into a closed package with closure::fromcallable ()
Closure adds a static method to quickly convert callable to a closure object.

Class Test {public    function exposefunction () {        return closure::fromcallable ([$this, ' privatefunction ']);    }    Private Function Privatefunction ($param) {        var_dump ($param);}    } $privFunc = (new Test)->exposefunction (); $privFunc (' some value ');

The above routines will output:

String ("some value")

10, asynchronous signal processing asynchronous signal handling

A new function called Pcntl_async_signals () have been introduced to enable asynchronous signal handling without using ticks (which introduce a lot of overhead).
Added a new function pcntl_async_signals () to handle the asynchronous signal, no need to use ticks (it will increase resource usage)

Pcntl_async_signals (TRUE); Turn on async signalspcntl_signal (SIGHUP,  function ($sig) {    echo "sighup\n";}); Posix_kill (Posix_getpid (), SIGHUP);

The above routines will output:

SIGHUP

11, HTTP/2 server push support Ext/curl

Support for server push have been added to the CURL extension (requires version 7.46 and above). This can is leveraged through the curl_multi_setopt () function with the new Curlmopt_pushfunction constant. The constants CURL_PUST_OK and Curl_push_deny has also been added so that the execution of the server PUSH callback can E Ither be approved or denied.
Translation:
Added to the curl extension for server push support (requires version 7.46 and above).
You can use the curl_multi_setopt () function by using the new Curlmopt_pushfunction constant.
Also added constants CURL_PUST_OK and Curl_push_deny to approve or reject the execution of server push callbacks

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.