New features added to PHP 7

Source: Internet
Author: User
Tags integer division php 7 features scalar
This article mainly introduces the new addition of PHP 7 features, has a certain reference value, now share to everyone, the need for friends can refer to a

Scalar type declaration

PHP 7 The parameter type declaration for a function in can be a scalar. In PHP 5 , only the class name, interface,array , or callable (PHP5.4, which can be functions, including anonymous functions ), you can now also use string,int,float , and bool out.

<?php//Force mode function sumofints (int ... $ints) {    return array_sum ($ints);} var_dump (Sumofints (2, ' 3 ', 4.1));

The above example will output:

int (9)

It is important to note that the problem of the strict pattern mentioned above is also applicable here: Coercion mode (default, coercion of type conversions), coercion of type conversions for parameters that do not conform to expectations, triggering in strict mode TypeError fatal error.

return value type declaration

PHP 7 added 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.

<?php function 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 example will output:

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

NULL Merge Operators

because there is a large number of simultaneous use of ternary expressions and isset () the situation, NULL The merge operator causes the variable to exist and the value is not NULL , it returns its own value, otherwise it returns its second operand.

Examples are as follows:

<?php//if $_get[' user ' does not exist return ' nobody ', return the value of $_get[' user '] $username = $_get[' user ']?? ' Nobody ';//similar ternary operator $username = isset ($_get[' user ')? $_get[' user ']: ' nobody ';? >

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 .

Examples are as follows:

<?php//integer echo 1<=>1;//0echo 1<=>2;// -1echo 2<=>1;//1//floating-point echo 1.5<=>1.5;//0echo 1.5<= >2.5;// -1echo 2.5<=>1.5;//1//String echo "a" <=> "a";//0echo "a" <=> "B";// -1echo "B" <=> "a";//1 ?>

through define () defining a constant array

Examples are as follows:

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

Anonymous class

now supported by New Class to instantiate an anonymous class with the following example:

<?phpinterfacelogger{    publicfunction Log (string $msg);} classapplication{    private $logger;     Publicfunction GetLogger (): logger{         return $this->logger;    }     Publicfunction Setlogger (Logger $logger) {         $this->logger = $logger;    }} $app =newapplication; $app Setlogger (newclassimplementslogger{    publicfunction log (string $msg) {        echo $msg;    }}); Var_dump ($app- >getlogger ());? >

The above example will output:

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

Unicode codepoint Translation Grammar

this takes a - in the form of Unicodecodepoint , and print out a double quote or Heredoc surrounded by UTF-8 a string encoded in the format. Any valid codepoint can be accepted , and 0 of the beginning can be omitted.

echo "\u{aa}"; echo "\U{0000AA}"; echo "\u{9999}";

The above example will output:

ªª (same as before but with optional leading 0 ' s)
Incense

Closure::call ()

Closure::call () There is now a better performance, a short, skilful way to temporarily bind a method to an object to close the packet and invoke it.

<?phpclass A {private $x =1;}//Pre PHP7 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 example will output:

11

to be unserialize () Provide filtering

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//Convert object to __php_incomplete_class object $data = Unserialize ($foo, ["allowed_classes" =>false]); The conversion object is a __php_incomplete_class object, except for MyClass and Myclass2$data = Unserialize ($foo, ["Allowed_classes" =>["MyClass", " MyClass2 "]); The default accepts all classes $data = Unserialize ($foo, ["allowed_classes" =>true]);

Intlchar

the newly added Intlchar class is designed to expose more ICU function. This class itself defines a number of static methods used to manipulate Unicode characters for multiple character sets .

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

The above example will output:

10ffffCOMMERCIAL Atbool (True)

to use this class, first install the Intl Extended

Expected

It is expected to use backwards and enhance the previous assert () the method. It enables the assertion to be zero-cost in a production environment, and provides the ability to throw specific exceptions when an assertion fails.

<?phpini_set (' assert.exception ', 1); classcustomerrorextendsassertionerror{} assert (False,newcustomerror (' Someerror message '));? >

The above example will output:

Fatalerror:uncaught customerror:some Error message

Use Strengthen

from the same namespace imported classes, functions, and constants are now available through a single Use Statement imported once.

<?php//  PHP 7 Prior version usage use Some\namespace\classa;use some\namespace\classb;use some\namespace\classc as C; Usefunction some\namespace\fn_a;usefunction some\namespace\fn_b;usefunction Some\namespace\fn_c; Useconst some\namespace\consta;useconst Some\namespace\constb;useconst SOME\NAMESPACE\CONSTC; PHP 7+ usage some\namespace\{classa,classb,classcas c};usefunction some\namespace\{fn_a, Fn_b, Fn_c};useconst some\ NAMESPACE\{CONSTA,CONSTB,CONSTC};? >

Generator Strengthen

enhances the Generator features, this can achieve many advanced features

<?php<?php function Gen () {    yield1;    Yield2;     Yieldfrom Gen2 ();} function Gen2 () {    yield3;    Yield4;} foreach (Gen () as $val) {    echo $val, Php_eol;}?>

The above example will output:

1234

Divisible

added an integer division function intp (), usage Examples:

<?phpvar_dump (INTP (10,3));? >

The above example will output:

Int (3)

Related recommendations:

New in PHP 5.4 adds the ability to judge the session state

Related Article

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.