Table of Contents
PHP scalar type and return value type declaration
PHP 7 use 语句
Home Backend Development PHP7 Let's take a look at the new features of php7

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

Jun 22, 2020 pm 05:42 PM
markdown php rear end Safety

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles
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)