Home > Backend Development > PHP7 > body text

Let's take a look at the new features of php7

coldplay.xixi
Release: 2023-02-17 16:06:01
forward
3456 people have browsed it

Let's take a look at the new features of php7

1. PHP scalar type and return value type declaration

2. PHP NULL coalescing operator

3. PHP spaceship operation operator (combination comparison operator)

4, PHP constant array

5, PHP anonymous class

6, PHP Closure::call()

7 , PHP filter unserialize()

8, PHP IntlChar()

9, PHP CSPRNG

10, PHP 7 exception

11, PHP 7 use Statement

12, PHP 7 error handling

13, PHP intp() function

14, PHP 7 Session options

15, PHP 7 deprecated features

16. Extensions removed in PHP 7

17. SAPI removed in PHP 7

PHP scalar type and return value type declaration

  • Scalar type declaration

    Forced mode

  • ##
declare(strict_types=1)
  <?php 
// 强制模式 
function sum(int ...$ints) 
{ 
   return array_sum($ints); 
} 
print(sum(2, &#39;3&#39;, 4.1)); 
?>

以上程序执行输出结果为:

9复制代码
Copy after login
  • Strict Mode

<?php 

declare(strict_types=1); 

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

print(sum(2, &#39;3&#39;, 4.1)); 
?>
以上程序由于采用了严格模式,所以如果参数中出现不适整数的类型会报错,执行输出结果为:

PHP Fatal error:  Uncaught TypeError: Argument 2 passed to sum() must be of the type integer, string given, called in……复制代码
Copy after login
PHP NULL coalescing operator

  • Previous ternary operation

  $site = isset($_GET['site']) ? $_GET['site'] : '菜鸟教程';复制代码
Copy after login
  • The current merge operator

  $site = $_GET['site'] ?? '菜鸟教程';复制代码
Copy after login
  • The above 2 methods are the same

  • The following are examples:

    <?php
// 获取 $_GET[&#39;site&#39;] 的值,如果不存在返回 &#39;高压锅&#39;$site = $_GET[&#39;site&#39;] ?? &#39;高压锅&#39;;print($site);print(PHP_EOL); // PHP_EOL 为换行符


// 以上代码等价于$site = isset($_GET[&#39;site&#39;]) ? $_GET[&#39;site&#39;] : &#39;高压锅&#39;;print($site);print(PHP_EOL);
// ?? 链$site = $_GET[&#39;site&#39;] ?? $_POST[&#39;site&#39;] ?? &#39;高压锅&#39;;print($site);
?>复制代码
Copy after login
Combined comparison operator, also known as spaceship operator

PHP 7 newly added spaceship operator ( The 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, 0, or 1 respectively.

The following is an 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);
?>复制代码
Copy after login
    以上结果分别为复制代码
Copy after login
0
-1
1

0
-1
1

0
-1
1复制代码
Copy after login
PHP constant array

  • Previously defined constant arrays could only have

    const;

  • Now to define a constant array you can use

    define();

The following is Example:

// 使用 define 函数来定义数组
define('sites', [   'Google',   'Runoob',   'Taobao']);print(sites[1]);
?>
以上程序执行输出结果为:

Runoob复制代码
Copy after login
PHP Anonymous Class

  • PHP 7 supports instantiating an anonymous class through new class, which can be used to replace some "use it immediately" The complete class definition of "burn".

  • The following is an 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("我的第一条日志"); 
        ?>
以上程序执行输出结果为:

我的第一条日志复制代码
Copy after login
php Closure::call()

  • PHP 7 The

    Closure::call() has better performance, dynamically binds a closure function to a new object instance and calls the function.

实例
<?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); 
?>
以上程序执行输出结果为:
1
1复制代码
Copy after login
PHP filter unserialize()

  • PHP 7 has added features that can provide filtering for

    unserialize(), It can prevent code injection of illegal data and provide safer deserialized data.

  • 实例
    <?php 
    class MyClass1 {  
       public $obj1prop;    
    } 
    class MyClass2 { 
       public $obj2prop; 
    } 
    
    
    $obj1 = new MyClass1(); 
    $obj1->obj1prop = 1; 
    $obj2 = new MyClass2(); 
    $obj2->obj2prop = 2; 
    
    $serializedObj1 = serialize($obj1); 
    $serializedObj2 = serialize($obj2); 
    
    // 默认行为是接收所有类 
    // 第二个参数可以忽略 
    // 如果 allowed_classes 设置为 false, unserialize 会将所有对象转换为 __PHP_Incomplete_Class 对象 
    $data = unserialize($serializedObj1 , ["allowed_classes" => true]); 
    
    // 转换所有对象到 __PHP_Incomplete_Class 对象,除了 MyClass1 和 MyClass2 
    $data2 = unserialize($serializedObj2 , ["allowed_classes" => ["MyClass1", "MyClass2"]]); 
    
    print($data->obj1prop); 
    print(PHP_EOL); 
    print($data2->obj2prop); 
    ?>
    以上程序执行输出结果为:
    1
    2复制代码
    Copy after login
Note that the above features are

unserialize() There is an additional parameter selection allowed_classes

PHP CSPRNG Pseudo-random number generator

  • 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.

  • In summary, it is similar to the original

    rand() and 'mt_rand()'; except that now random_bytes() generates a random string

php7 Exceptions

  • PHP 7 exceptions are used for backward compatibility and enhancement of the old

    assert() function. It enables zero-cost assertions in production environments and provides the ability to throw custom exceptions and errors.

  • Old versions of the API will continue to be maintained for compatibility purposes.

  • assert() is now a language construct that allows the first argument to be an expression, not just a string to be evaluated or a boolean to be tested.

  • assert()的应用  跟assert_option() 配合复制代码
    Copy after login
There are also parameter types

Configuration itemsDefault valueOptional Values ​​zend.assertions11. Generate and execute code (development mode) assert.exception01. Thrown when the assertion fails, an exception object can be thrown. If no exception is provided, an AssertionError object instance is thrown.
**参数**
assertion
断言。在 PHP 5 中,是一个用于执行的字符串或者用于测试的布尔值。在 PHP 7 中,可以是一个返回任何值的表达式, 它将被执行结果用于指明断言是否成功。
description
如果 assertion 失败了,选项 description 将会包括在失败信息里。
exception
在 PHP 7 中,第二个参数可以是一个 Throwable 对象,而不是一个字符串,如果断言失败且启用了 assert.exception 该对象将被抛出

实例
将 zend.assertions 设置为 0:
实例
<?php 
ini_set(&#39;zend.assertions&#39;, 0); 

assert(true == false); 
echo &#39;Hi!&#39;; 
?>
以上程序执行输出结果为:
Hi!
将 zend.assertions 设置为 1,assert.exception 设置为 1:
实例
<?php 
ini_set(&#39;zend.assertions&#39;, 1); 
ini_set(&#39;assert.exception&#39;, 1); 

assert(true == false); 
echo &#39;Hi!&#39;; 
?>
以上程序执行输出结果为:
Fatal error: Uncaught AssertionError: assert(true == false) in -:2
Stack trace:#0 -(2): assert(false, &#39;assert(true == ...&#39;)#1 {main}
  thrown in - on line 2复制代码
Copy after login

PHP 7 use 语句

  • PHP 7 可以使用一个 use 从同一个 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}; 
?>
Copy after login

推荐教程:《php教程

The above is the detailed content of Let's take a look at the new features of php7. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.im
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!
0. Generate code, but skip it during execution
-1. Do not generate code (production environment)
0 . Use or generate Throwable, just generate warnings based on the object instead of throwing the object (compatible with PHP 5)