New features of PHP7

Keywords: PHP Session curl JSON

From http://blog.csdn.net/fenglailea/article/details/52717364

PHP7.0
New features
1. Empty merge operator (??)

Simplify Judgment

$param = $_GET['param'] ?? 1;

Amount to:

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

2. Variable type declaration

Two modes: mandatory (default) and strict
Types: string, int, float, and bool

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

3. Return value type declaration

Both functions and anonymous functions can specify the type of 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. Space Ship Operators (Combinatorial Comparators)

The space ship 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 general comparison rules of PHP.

// Integers
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1
// Floats
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1
// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1

5. Anonymous classes

Instantiating an anonymous class through a new class is now supported, which can be used as an alternative to some complete class definitions of "burn-as-you-go".

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 $msg;
    }
});
var_dump($app->getLogger());

6.Unicode codepoint translation syntax

This accepts a Unicode codepoint in hexadecimal form and prints a string in UTF-8 encoding format surrounded by double quotes or heredoc s.Any valid codepoint can be accepted, and the starting zero can be omitted.

 echo "\u{9876}"

Old Output: u{9876}
New version input: top
7.Closure::call()

Closure::call() now has better performance by briefly and concisely temporarily binding a method to an object to close it and call it.

class Test
{
    public $name = "lixuan";
}

//Both PHP7 and PHP5.6 are available
$getNameFunc = function () 
{
    return $this->name;
};
$name = $getNameFunc->bindTo(new Test, 'Test');
echo $name();

//PHP7 OK, PHP5.6 error
$getX = function () 
{
    return $this->name;
};
echo $getX->call(new Test);

8. Provide filtering for unserialize()

This feature is designed to provide a more secure way to unpack unreliable data.It prevents potential code injection by whitelisting.

//Divide all objects into u PHP_Incomplete_Class objects
$data = unserialize($foo, ["allowed_classes" => false]);
//Divide all objects into u 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 new IntlChar class is designed to expose more ICU functionality.This class itself defines a number of static methods for manipulating unicode characters in a multicharacter set.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 output:

10ffff
COMMERCIAL AT
bool(true)

10. Expectations

It is expected that the previous assert() method will be used backwards and enhanced.It enables assertions to be zero cost enabled in a production environment and provides the ability to throw specific exceptions when assertions fail.Older versions of API s will continue to be maintained for compatibility purposes, and assert() is now a language structure that allows the first parameter to be an expression, not just a string to be calculated 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 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 at once through a single use statement.

//Before PHP7
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;

// After PHP7
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.intdiv()

Receives two parameters as dividends and dividends, returning the integer part of their division result.

var_dump(intdiv(7, 2));

Output int(3)
13.CSPRNG

Two new functions have been added: random_bytes() and random_int(). Production protected integers and strings that can be encrypted.All in all, random numbers become safe.
random_bytes - Encrypted pseudo-random string whose survival is protected
random_int - Pseudo-random integer whose cryptographic survival is protected
14,preg_replace_callback_array()

A new function, preg_replace_callback_array(), has been added to make code more elegant when using the preg_replace_callback() function.Prior to PHP7, callback functions called every regular expression and were contaminated on some branches.
15,Session options

The session_start() function can now accept an array as a parameter and override the session's configuration item in php.ini.
For example, set the cache_limiter to private and close it immediately after reading the session.

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

16. Return value of generator

The concept of generator was introduced in PHP5.5.The generator function gets a value identified by the yield for each execution.In PHP7, when the generator iteration is complete, the return value of the generator function can be obtained.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. Additional generators were introduced into the generator

Another generator or generators can be introduced in the generator by writing yield from functionName1 only

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 defining ()

define('ANIMALS', ['dog', 'cat', 'bird']);
echo ANIMALS[1]; // outputs "cat"

Incompatibility
1. foreach no longer changes the internal array pointer

Prior to PHP7, when the array iterates through foreach, the array pointer moves.Now, not anymore, see the code below.

$array = [0, 1, 2];
foreach ($array as &$val) {
    var_dump(current($array));
}

PHP5 output:

int(1)
int(2)
bool(false)

PHP7 output:

int(0)
int(0)
int(0)

2. foreach has better iteration properties when traversing by reference

When traversing arrays using references, foreach is now better able to track changes in iterations.For example, to add an iteration value to an array in an iteration, refer to the following code:

$array = [0];
foreach ($array as &$val) {
    var_dump($val);
    $array[1] = 1;
}

PHP5 output:

int(0)

PHP7 output:

int(0)
int(1)

3. Hexadecimal strings are no longer considered numbers

Strings containing hexadecimal digits are no longer considered numbers

var_dump("0x123" == "291");
var_dump(is_numeric("0x123"));
var_dump("0xe" + "0x1");
var_dump(substr("foo", "0x1"));

PHP5 output:

bool(true)
bool(true)
int(15)
string(2) "oo"

PHP7 output:

bool(false)
bool(false)
int(0)
Notice: A non well formed numeric value encountered in /tmp/test.php on line 5
string(3) "foo"

4. Functions removed in PHP7

The list of functions removed is as follows:
call_user_func() and call_user_func_array() have been discarded since PHP 4.1.0.
The obsolete mcrypt_generic_end() function has been removed, use mcrypt_generic_deinit() instead.
The obsolete mcrypt_ecb(), mcrypt_cbc(), mcrypt_cfb(), and mcrypt_ofb() functions have been removed.
set_magic_quotes_runtime(), along with its alias magic_quotes_runtime(), has been removed. They have been discarded in PHP 5.3.0 and are also disabled in PHP 5.4.0 due to discarded magic quotes.
The obsolete set_socket_blocking() function has been removed, use stream_set_blocking() instead.
dl() is no longer available in PHP-FPM and is still available in CLI and embedded SAPIs.
The following functions were removed from the GD library: imagepsbbox(), imagepsencodefont(), imagepsextendfont(), imagepsfreefont(), imagepsloadfont(), imagepsslantfont(), imagepstext().
In the configuration file php.ini, always_populate_raw_post_data, asp_tags, xsl.security_prefs were removed.
5. Objects created by the new operator cannot be assigned to variables by reference

Objects created by the new operator cannot be assigned to variables by reference

class C {}
$c =& new C;

PHP5 output:

Deprecated: Assigning the return value of new by reference is deprecated in /tmp/test.php on line 3

PHP7 output:

Parse error: syntax error, unexpected 'new' (T_NEW) in /tmp/test.php on line 3

6. Remove ASP and script PHP Tags

The use of ASP-like tags and script tags to distinguish PHP code has been removed.The tags affected are: <%>, <%=%>,
7. Initiate calls from unmatched contexts

Statically invoking a non-static method in an unmatched context is obsolete in PHP 5.6, but in PHP 7.0 it results in an undefined $this variable in the called method and a warning that this behavior has been obsoleted.

class A {
    public function test() { var_dump($this); }
}

// Note: Not inherited from class A
class B {
    public function callNonStaticMethodOfA() { A::test(); }
}
(new B)->callNonStaticMethodOfA();

PHP5 output:

Deprecated: Non-static method A::test() should not be called statically, assuming $this from incompatible context in /tmp/test.php on line 8
object(B)#1 (0) {
}

PHP7 output:

Deprecated: Non-static method A::test() should not be called statically in /tmp/test.php on line 8
Notice: Undefined variable: this in /tmp/test.php on line 3
NULL

8. Internal function will fail when the value overflows

When converting a floating point number to an integer, if the floating point value is too large to be expressed as an integer, the internal function truncated the integer directly in previous versions without causing errors.In PHP 7.0, if this happens, it will cause an E_WARNING error and return NULL.
9. JSON extensions have been replaced by JSOND

The JSON extension has been replaced by the JSOND extension.
There are two points to note when dealing with numerical values:
First, a number cannot end with a dot (.) (for example, a value of 34.0 or 34 must be written).
Second, if you use scientific notation to represent values, e must not be preceded by a dot (.) (for example, 3.e3 must write 3.0e3 or 3e3).
10. Remove #comment format from INI file

Comment lines starting with # are no longer supported in the profile INI file. Use; (semicolon) to represent comments.This change applies to php.ini and files processed with the parse_ini_file() and parse_ini_string() functions.
11, $HTTP_RAW_POST_DATA removed

The $HTTP_RAW_POST_DATA variable is no longer provided.Use php://input as an alternative.
12. yield changed to right join operator

When using the yield keyword, parentheses are no longer required and it changes to the right join operator, which has operator precedence between print and =>.This may change the behavior of existing code.You can disambiguate by using parentheses.

echo yield -1;
// In previous versions it was interpreted as:
echo (yield) - 1;
// Now it will be interpreted as:
echo yield (-1);
yield $foo or die;
// In previous versions it was interpreted as:
yield ($foo or die);
// Now it will be interpreted as:
(yield $foo) or die;

PHP7.1.x
New features
1. Nullable type

Types are now allowed to be empty, and when this feature is enabled, the incoming parameter or function returns either the given type or null.You can make it empty by preceding the type with a question mark.

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

The above routines output:

string(5) "tpunt"
NULL
Uncaught Error: Too few arguments to function test(), 0 passed in...

2.Void functions

On the basis of the other return value types introduced in PHP 7, a new return value type, void, was introduced.Methods that declare return values as void type either simply omit the return statement or use an empty return statement.null is not a valid return value for void functions.

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

null
int(2)
int(1)

Trying to get the return value of a void method will result in null and no warning.The reason for this is that you don't want to affect a higher-level approach.
3. Short array syntax Symmetric array destructuring

The short array syntax ([]) can now be used to assign values of arrays to variables, including foreach.This makes it easier to extract values from an array.

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

4. Class Constant Visibility

Setting the visibility of class constants is now supported.

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) has been introduced.This can be used in parameter or return value types, which represent objects that accept arrays or implement the Traversable interface.As for subclasses, when used as parameters, subclasses can tighten the Iterable type of the parent class to array or an object that implements Traversable.For return values, the subclass can widen the array of the parent class or the return value type of the object to iterable.

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

6. Multiple exception capture processing

A catch statement block can now capture multiple exceptions using the pipe character (|).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

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

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

8. Support for negative string offsets

All string-based functions built into offset now support accepting negative numbers as offsets, including array dereference operators ([]).

var_dump("abcdef"[-2]);
var_dump(strpos("aabbcc", "b", -3));

The above routines output:

string (1) "e"
int(3)

9.ext/openssl support for AEAD

AEAD (mode GCM and CCM) is now supported by adding additional parameters to openssl_encrypt() and openssl_decrypt().
Convert callables to closures by Closure::fromCallable()
Closure adds a static method for quickly turning a callable into 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 output:

string(10) "some value"

10. Asynchronous signal handling for asynchronous signal processing

A new function called pcntl_async_signals() has been introduced to enable asynchronous signal handling without using ticks (which introduce a lot of overhead).
A new function, pcntl_async_signals(), has been added to handle asynchronous signals without requiring ticks (which will increase resource usage)

pcntl_async_signals(true); // turn on async signals
pcntl_signal(SIGHUP,  function($sig) {
    echo "SIGHUP\n";
});
posix_kill(posix_getpid(), SIGHUP);

The above routines output:

SIGHUP

11.HTTP/2 Server Push Support ext/curl

Support for server push has been added to the CURL extension (requires version 7.46 and above). This can be leveraged through the curl_multi_setopt() function with the new CURLMOPT_PUSHFUNCTION constant. The constants CURL_PUST_OK and CURL_PUSH_DENY have also been added so that the execution of the server push callback can either be approved or denied.
Bad English:
Add support for server push to curl extensions (version 7.46 and above is required).
The curl_multi_setopt() function can be used by using the new CURLMOPT_PUSHFUNCTION constant.
Constant CURL_PUST_OK and CRL_PUSH_DENY have also been added to approve or reject the execution of server push callbacks

Incompatibility
1. An error will be thrown when too few parameters are passed

In the past, if we invoked a user-defined function with insufficient parameters, a warning would be raised.This warning is now elevated to an Error exception.This change takes effect only for user-defined functions and does not include built-in functions.For example:

function test($param){}
test();

Output:

Uncaught Error: Too few arguments to function test(), 0 passed in %s on line %d and exactly 1 expected in %s:%d

2. Prevent dynamic function calls

Prevent dynamic invocation of functions as follows

assert() - with a string as the first argument
compact()
extract()
func_get_args()
func_get_arg()
func_num_args()
get_defined_vars()
mb_parse_str() - with one arg
parse_str() - with one arg

(function () {
    'func_num_args'();
})();

output

Warning: Cannot call func_num_args() dynamically in %s on line %d

3. Invalid class, interface, trait name

The following names cannot be used for class, interface, or trait names:

void
iterable

4.Numerical string conversions now respect scientific notation

Integer operations and conversions on numerical strings now respect scientific notation. This also includes the (int) cast operation, and the following functions: intval() (where the base is 10), settype(), decbin(), decoct(), and dechex().

5.mt_rand algorithm repair

mt_rand() will now default to using the fixed version of the Mersenne Twister algorithm. If deterministic output from mt_srand() was relied upon, then the MT_RAND_PHP with the ability to preserve the old (incorrect) implementation via an additional optional second parameter to mt_srand().

6.rand() alias mt_rand() and srand() alias mt_srand()

rand() and srand() have now been made aliases to mt_rand() and mt_srand(), respectively. This means that the output for the following functions have changes: rand(), shuffle(), str_shuffle(), and array_rand().

7.Disallow the ASCII delete control character in identifiers

The ASCII delete control character (0x7F) can no longer be used in identifiers that are not quoted.

8.error_log changes with syslog value

If the error_log ini setting is set to syslog, the php error levels are mapped to the syslog error levels. This brings finer differentiation in the error logs in contrary to the previous approach where all the errors are logged with the notice level only.

9. Deconstruction methods are no longer called on incomplete objects

A destructor will no longer be called on an incomplete object, such as throwing an exception in a construction method
10.call_user_func() no longer supports calls to addressed functions

call_user_func() will now always fail when calling a function that takes a reference as an argument.
11. String no longer supports The empty index operator is not supported for strings anymore

Using an empty index operator on a string, such as str[]=x, will throw a fatal error instead of silently converting it to an array
12.ini Configuration Item Removal

The following ini configuration items have been removed:

session.entropy_file
session.entropy_length
session.hash_function
session.hash_bits_per_character

Abandoned features in PHP 7.1.x
1.ext/mcrypt

The mcrypt extension has been obsolete for about 10 years and is complex to use.Therefore, it is obsolete and replaced by OpenSSL.Beginning with PHP 7.2, it will be removed from core code and moved to PECL.
Eval options for 2.mb_ereg_replace() and mb_eregi_replace()

The e-mode modifiers for mb_ereg_replace() and mb_eregi_replace() are now obsolete

PHP official website documentation: http://php.net/manual/zh/migration70.php
You can browse PHP5.6 to PHP7 for new features, new functions, removed functions, incompatibilities, new classes and interfaces, etc.
source
http://www.lanecn.com/article/main/aid-97
http://php.net/manual/zh/migration71.php

Posted by Hitch54 on Sat, 25 May 2019 10:50:55 -0700