PHP5.5 ~ PHP7.2 New Characteristics Finishing ____php

Source: Internet
Author: User
Tags closure generator integer division iterable scalar

http://php.net/manual/zh/appendices.php from PHP 5.5.x porting to PHP 5.6.x new features using expression to define constants in previous versions of PHP, must You must use static values to define constants, declare properties, and specify default values for function parameters. You can now define constants, declare properties, and set function parameter defaults by using numeric expressions that include numeric values, string literals, and other constants.

<?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 by using the Const keyword.
<?php
Const ARR = [' A ', ' B '];

Echo Arr[0];
Use the ... operator defines variable-length parameter functionsNow can not rely on Func_get_args (), use ... operator to implement variable-length parameter functions.
<?php
function f ($req, $opt = null, ... $params) {
    //$params is an array containing the remaining parameters
    printf (' $req:%d; $opt:%d; n Umber of params:%d '. ' \ n ",
           $req, $opt, Count ($params));
}

f (1);
F (1, 2);
F (1, 2, 3);
F (1, 2, 3, 4);
? >

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
Use the ... Operator for parameter expansionWhen calling a function, use the ... operator to expand an array and an Ergodic object into a function argument. In other programming languages, such as Ruby, this is called a concatenation operator.
<?php
function 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 constThe use operator is extended to support the import of external functions and constants in the class. The corresponding structure is the use function and the use Const.
<?php
namespace Name\space {
    const FOO =;
    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:

name\space\f
using Hash_equals () to compare strings to avoid timing attacks porting from PHP 5.6.x to PHP 7.0.x new Features scalar type declarationThere are two modes of scalar type declarations: coercion (default) and strict mode. You can now use the following type parameters, whether in mandatory or strict mode: string, Integer (int), floating-point number (float), and Boolean value (BOOL).
<?php
//Coercive mode
function sumofints (int ... $ints) {return
    array_sum ($ints);
}

Var_dump (sumofints (2, ' 3 ', 4.1));

The above routines will output:

Int (9)
return value type declarationPHP 7 adds support for the return type declaration. Similar to a parameter type declaration, a return type declaration indicates the type of the function return value. The available types are the same as those available in the parameter declaration.
<?php

function arrayssum (array ... $arrays): array {return
    Array_map (function (array $array): int { C17/>return array_sum ($array);
    }, $arrays);
}
null merge operatorBecause of the large number of simultaneous use of ternary expressions and isset () in everyday use, we have added the syntactic 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 is equivalent to:
$username = isset ($_get[' user '])? $_get[' user ': ' Nobody ';

Coalesces can be chained:this would return the ' the ' of the ' defined ' of $_get[' user ', $_post[' user ', and ' nobody '. c5/> $username = $_get[' user ']?? $_post[' user ']?? ' Nobody ';
? >
spacecraft operator (combination comparison character)The spacecraft operator is used to compare two expressions. It returns 1, 0, or 1, respectively, when a is less than, equal to, or greater than a, equal to or greater than a is less than, equal to, or greater than B. The principle of comparison is to follow the regular comparison rules of PHP.
<?php
//Integer
echo 1 <=> ' 1 ';//0
Echo 1 <=> 2;//-1
Echo 2 <=> 1;//1

//floating-point number 
  echo ' 1.50 ' <=> 1.5; 0
Echo 1.5 <=> 2.5;//1
echo 2.5 <=> 1.5;//1

//String
echo "a" <=> "a";//0
E Cho "a" <=> "B"; -1
echo "B" <=> "a";//1
?>
defining a constant array by define ()Constants of Array types can now be defined by define (). Only the const definition can be used in PHP5.6.
Define (' ANIMALS ', [
    ' dog ', '
    cat ',
    ' bird '
]);

Echo Animals[1]; Output "Cat"
Closure::call ()Closure::call () now has better performance, a short and able temporary binding method to the object closure and call it.
<?php
class A {private $x = 1;}

PHP 7 Previous version of the code
$getXCB = function () {return $this->x;};
$getX = $getXCB->bindto (new A, ' a '); Middle-layer Closure
echo $getX ();

PHP 7+ and later code
$getX = function () {return $this->x;};
Echo $getX->call (new A);

The above routines will output:

1
Group Use DeclarationClasses, functions, and constants imported from the same namespace can now be imported one at a time through a single use statement.
<?php

//php 7 before the code 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+ and later versions of the code 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};
? >
The generator can return an expressionThis feature is built on the generator features introduced in the PHP 5.5 release. It allows you to return an expression (but not to return a reference value) in a builder function by calling the Generator::getreturn () method to get the return value of the generator, but this method can only be invoked once after the generator finishes generating work. Integer Division function intdiv () porting from PHP 7.0.x to PHP 7.1.x new Features Nullable (Nullable) typeParameters and the type of the return value can now be allowed to be empty by adding a question mark to the type. When this attribute is enabled, the incoming parameter or function returns the result either as a given type or as null.
<?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 routines will output:

String (a) "elephpant"
null
string (TEN) "Elephpant"
null
uncaught error:too few arguments to function test (), 0 passed in ...
Void functionA new return value type void was introduced. A method that declares a void type either omits a return statement altogether or uses an empty returns statement. For a void function, NULL is not a valid return value.
<?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 routines will output:

null
int (2)
int (1)
symmetric array destructuringThe short array Syntax ([]) is now an alternative to the list () syntax, which can be used to assign the value of an array to some variables (including in foreach).
<?php
$data = [
    [1, ' Tom '],
    [2, ' Fred '],
];

List () style
list ($id 1, $name 1) = $data [0];

[] Style
[$id 1, $name 1] = $data [0];

List () style
foreach ($data as List ($id, $name)) {
    //logic with $id and $name
}

//[] style
  foreach ($data as [$id, $name]) {
    //logic here with $id and $name
}
class constant VisibilityThe visibility of the set class constants is now supported.
<?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 Pseudo classA 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 the Traversable interface. As for subclasses, when used as arguments, subclasses can tighten the iterable type of the parent class to an array or an object that implements the traversable. For return values, subclasses can widen the array or object return value type of the parent class to iterable.
<?php
function iterator (iterable $iter): iterable
{
    foreach ($iter as $val) {
        //
    }
}
Multi-exception capture processingA 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.
<?php
try {
    //some code
} catch (Firstexception | Secondexception $e) {
    //handle and second exceptions
}
list () now supports key namesNow the list () and its new [] syntax support the designation of key names within it. This means that it can assign an array of any type to a variable (similar to a short array syntax)
<?php
$data = [
    ["id" => 1, "name" => ' Tom '],
    ["id" => 2, "name" => ' Fred '],
];

List () style
list ("id" => $id 1, "name" => $name 1) = $data [0];

[] Style
["id" => $id 1, "name" => $name 1] = $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
}
porting from PHP 7.1.x to PHP 7.2.x new Features New Object TypeThis new object type, objects, is introduced to return any object type that can be used for contravariant (contravariant) parameter inputs and covariant (covariant).
<?php

function Test (object $obj): Object
{return
    new Splqueue ();
}

Test (New StdClass ());
allow overriding abstract methodsWhen an abstract class inherits from another abstract class, an inherited abstract class can override an abstract method of an inherited abstract class.
Abstract class A
{
    abstract function test (string $s);
Abstract class B extends A
{
    //Overridden-still maintaining contravariance for parameters and covariance for re Turn
    abstract function test ($s): int;
}
parameter types are extendedThe parameter types that override methods and interface implementations can now be omitted. However, this is still compliant with LSP because the parameter type is now contravariant.
Interface A
{public
    function Test (array $input);
}

Class B implements A
{public
    function Test ($input) {}/type omitted for $input
}
allow trailing commas for grouping namespacesNamespaces can be introduced in PHP 7 using trailing commas in groups.
Use foo\bar\{
    Foo,
    Bar,
    Baz,
};

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.