New features in PHP7


1. Core

  • Added group use syntax statement. RFC: https://wiki.php.net/rfc/group_use_declarations
  • Added null coalescing operator??. RFC: https://wiki.php.net/rfc/isset_ternary
  • 64-bit PHP7 string length can exceed 2^31 bytes.
  • Added Closure::call() method.
  • Double-quoted strings and heredocs support using \u{xxxxx} to declare unicode characters.
  • define() can define an array as a constant.
  • Added merge comparison operator <=>. RFC: https://wiki.php.net/rfc/combined-comparison-operator
  • Added yield from operator. https://wiki.php.net/rfc/generator-delegation
  • Keywords can also be used in specific scenarios. RFC: https://wiki.php.net/rfc/context_sensitive_lexer
  • Added scalar type declaration function. RFC: https://wiki.php.net/rfc/scalar_type_hints_v5
  • Added interface to provide a safe and convenient random number generator for the user layer. RFC: https://wiki.php.net/rfc/easy_userland_csprng


# ①PHP scalar type and return value type declaration

Scalar type declaration

Default , all PHP files are in weak type checking mode.

PHP 7 adds the feature of scalar type declaration. There are two modes for scalar type declaration:

  • Forced mode (default) strict mode

  • Strict mode

Scalar type declaration syntax format:

declare(strict_types=1);

By specifying the value of strict_types (1 or 0) in the code, 1 indicates strict type checking mode, which applies to function calls and return statements; 0 indicates weak type checking mode.

The type parameters that can be used are:

  • #int

  • ##float
  • bool
  • string
  • interfaces
  • array
  • callable
Force mode example:

<?php
// 强制模式
function sum(int ...$ints)
{
   return array_sum($ints);
}
print(sum(2, '3', 4.1));
?>
The above program execution output result is:

9

The example summary will Parameter 4.1 is converted to an integer 4 and then added.

Strict mode example:

<?php
// 严格模式
declare(strict_types=1);

function sum(int ...$ints)
{
   return array_sum($ints);
}

print(sum(2, '3', 4.1));
?>
Since the above program adopts strict mode, if an inappropriate integer type appears in the parameter, an error will be reported, and the execution output result is:

PHP Fatal error:  Uncaught TypeError: Argument 2 passed to sum() must be of the type integer, string given, called in……


Return type declarationPHP 7 adds support for return type declaration, which specifies the function return The type of value.

The return types that can be declared are:

    #int
  • ##float
  • bool
  • string
  • interfaces
  • array
  • callable
  • Return type declaration example:

In the example, the return result is required to be an integer:

<?php
declare(strict_types=1);
function returnIntValue(int $value): int
{
   return $value;
}
print(returnIntValue(5));
?>

The above program execution output result is:

5

Return type declaration error example:

<?php
declare(strict_types=1);

function returnIntValue(int $value): int
{
   return $value + 1.0;
}

print(returnIntValue(5));
?>

Since the above program adopts strict mode, the return value must be int, but the calculation result is float, so an error will be reported. The execution output result is:

Fatal error: Uncaught TypeError: Return value of returnIntValue() must be of the type integer, float returned...

②PHP NULL merging operator

PHP 7’s newly added NULL merging operator (??) is a shortcut for performing ternary operations detected by isset().

The NULL coalescing operator will determine whether the variable exists and the value is not NULL. If so, it will return its own value, otherwise it will return its second operand.

We used to write the ternary operator like this:

$site = isset($_GET['site']) ? $_GET['site'] : 'PHP中文网';

Now we can write it directly like this:

$site = $_GET['site'] ?? 'PHP中文网';

Example

<?php
// 获取 $_GET['site'] 的值,如果不存在返回 'PHP中文网'
$site = $_GET['site'] ?? 'PHP中文网';

print($site);
print(PHP_EOL); // PHP_EOL 为换行符

// 以上代码等价于
$site = isset($_GET['site']) ? $_GET['site'] : 'PHP中文网';

print($site);
print(PHP_EOL);
// ?? 链
$site = $_GET['site'] ?? $_POST['site'] ?? 'PHP中文网';

print($site);
?>

The execution output of the above program is:

PHP中文网
PHP中文网
PHP中文网

③PHP spaceship operator (combined comparison operator)

PHP 7’s newly added spaceship operator (combined comparison operator) is used to compare two expressions $a and $b. If $a is less than, equal to, or greater than $b, it returns -1 and 0 respectively. or 1.

Example

<?php
// 整型比较
print( 1 <=> 1);print(PHP_EOL);
print( 1 <=> 2);print(PHP_EOL);
print( 2 <=> 1);print(PHP_EOL);
print(PHP_EOL); // PHP_EOL 为换行符

// 浮点型比较
print( 1.5 <=> 1.5);print(PHP_EOL);
print( 1.5 <=> 2.5);print(PHP_EOL);
print( 2.5 <=> 1.5);print(PHP_EOL);
print(PHP_EOL);

// 字符串比较
print( "a" <=> "a");print(PHP_EOL);
print( "a" <=> "b");print(PHP_EOL);
print( "b" <=> "a");print(PHP_EOL);
?>

##The execution output of the above program is:

0
-1
1

0
-1
1

0
-1
1

④PHP constant array

In PHP 5.6, constant arrays can only be defined through const, and in PHP 7, they can be defined through define() .

Example

<?php// 使用 define 函数来定义数组define('sites', [
   'Google',
   'PHP',
   'Taobao']);print(sites[1]);?>

The execution output of the above program is:

PHP

⑤PHP Closure::call()

PHP 7’s Closure::call() has better performance and dynamically binds a closure function to a new object instance And call and execute the function.


Example

<?php
class A {
    private $x = 1;
}

// PHP 7 之前版本定义闭包函数代码
$getXCB = function() {
    return $this->x;
};

// 闭包函数绑定到类 A 上
$getX = $getXCB->bindTo(new A, 'A'); 

echo $getX();
print(PHP_EOL);

// PHP 7+ 代码
$getX = function() {
    return $this->x;
};
echo $getX->call(new A);
?>

The execution output of the above program is:

1
1

⑥PHP CSPRNG

##CSPRNG (Cryptographically Secure Pseudo-Random Number Generator, pseudo-random number generator).

PHP 7 provides a simple mechanism for generating cryptographically strong random numbers by introducing several CSPRNG functions.

  • random_bytes() - Cryptographically protected pseudo-random string.

  • random_int() - cryptographically protected pseudo-random integer

random_bytes()

Syntax format

string random_bytes ( int $length )

Parameters

  • length - The number of bytes returned by the random string.

Return value

  • Returns a string and accepts an int type input parameter to represent The number of bytes returned in the result.

Example

<?php
$bytes = random_bytes(5);
print(bin2hex($bytes));
?>

The execution output of the above program is :

6f36d48a29

random_int()

##Syntax format

int random_int ( int $min , int $max )

Parameters

    min - The minimum value returned, must be greater than or equal to PHP_INT_MIN.
  • max - The maximum value returned, must be less than or equal to PHP_INT_MAX .

Return value

    Returns an int number within the specified range.

Example

<?php
print(random_int(100, 999));
print(PHP_EOL);
print(random_int(-1000, 0));
?>
The execution output of the above program is:

723
-64


⑦PHP Anonymous ClassPHP 7 supports instantiating an anonymous class through new class, which can be used to replace some "burn after use" "'s complete class definition.

Example

<?php
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;
// 使用 new class 创建匿名类
$app->setLogger(new class implements Logger {
   public function log(string $msg) {
      print($msg);
   }
});
$app->getLogger()->log("我的第一条日志");
?>

The execution output of the above program is:

我的第一条日志


⑧PHP 7 use statement PHP 7 can use a use to import classes, functions and constants from the same namespace:

// PHP 7 之前版本需要使用多次 use
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+ 之后版本可以使用一个 use 导入同一个 namespace 的类
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};
?>

2. Opcache module


  • Added file-based secondary opcode caching mechanism. You can set opcache.file_cache=<DIR> in the php.ini file. When the service is restarted or SHM is reset, using the secondary file caching mechanism can improve performance.
  • You can also set opcache.file_cache_only=1 to limit the use of file cache only.
  • You can set the opcache.file_cache_consistency_checks=0 parameter to speed up loading.
  • You can set opcache.huge_code_pages=0/1 to decide whether to put PHP code pages into huge pages. http://www.laruence.com/2015/10/02/3069.html
  • The windows version adds the opcache.file_cache_fallback=1 configuration item.

3. OpenSSL module

Added the "alpn_protocols" option.

4. Reflection

  • The ReflectionGenerator class is added for yield from Traces, current file/line, etc.
  • The ReflectionType class has been added to better support new return values ​​and scalar declaration functions.

5. Streaming

The windows version adds the option of block reading. Can be activated by passing array("pipe" => array("blocking" => true)) parameter.