Home Backend Development PHP7 Summarize the new features of each version of PHP 7.x

Summarize the new features of each version of PHP 7.x

Feb 23, 2021 am 09:46 AM

Summarize the new features of each version of PHP 7.x

Recommended (free): PHP7

PHP 7.x each New features of the version

Preface

Last month my colleague saw me writing

$a = $a ?? '';
Copy after login

and asked me what the writing method was, and also like this How to write? I said this is a writing method that is only available in PHP7 and above. Don’t you know? He said he didn't know.

I muttered in my heart and planned to start writing this blog.

PHP7 should be a modern PHP in addition to the basics. Because in PHP7, strong type definitions and some grammatical writing methods, such as combined comparison operators, define() can define arrays and other features. The formal introduction begins below, starting with PHP7.0. New versions will be added in the future, and they will be added one after another.
Ok, let’s start

PHP 7.0

Scalar type declaration

What is a scalar type?

Four scalar types:
boolean (Boolean type)
integer (integer type)
float (floating point type, also called double)
string (character String)
Two composite types:
array (array)
object (object)
Resource is a special variable that holds a reference to an external resource. Resources are created and used through specialized functions. Resource type variables are special handles for opening files, database connections, graphics canvas areas, etc.
To put it more simply, a scalar type is a data type that defines variables.

In php5, there are class names, interfaces, arrays and callback functions. In PHP, strings, integers, floats, and bools have been added. Let's take an example below. See the example for everything

function typeInt(int $a){
    echo $a;}typeInt('sad');// 运行,他讲会报错 Fatal error: Uncaught TypeError: Argument 1 passed to type() must be of the type integer, string given
Copy after login

Here, we define that $a must be of type int. If string is passed in the type function, an error will be reported. Let's modify the above code.

function typeString(string $a){
    echo $a;}typeString('sad'); //sad
Copy after login

Return value type declaration

The method return value of the function can be defined. For example, a certain function of mine must return Int type, it will definitely return int. If you return string, an error will be reported. As follows

<?phpfunction returnArray(): array{

    return [1, 2, 3, 4];}print_r(returnArray());/*Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)
*/
Copy after login

What happens when we define an array and return string or other types?

Then he willreport an errorFor example

function returnErrorArray(): array
{

    return '1456546';
}

print_r(returnErrorArray());
/*
Array
Fatal error: Uncaught TypeError: Return value of returnArray() must be of the type array, string returned in 
*/
Copy after login

null merge operator

Due to the fact that there are a large number of three simultaneous uses in daily use In the case of metaexpressions and isset(), we add the syntactic sugar of the null coalescing operator (??). If the variable exists and is not NULL, it returns its own value, otherwise it returns its second operand.

<?php

$username = $_GET[&#39;user&#39;] ?? &#39;nobody&#39;;
//这两个是等效的  当不存在user 则返回?? 后面的参数

$username = isset($_GET[&#39;user&#39;]) ? $_GET[&#39;user&#39;] : &#39;nobody&#39;;

?>
Copy after login

Spaceship operator

// 整数echo 1 <=> 1; // 0 当左边等于右边的时候,返回0echo 1 <=> 2; // -1  当左边小于右边,返回-1echo 2 <=> 1; // 1  当左边大于右边,返回1// 浮点数echo 1.5 <=> 1.5; // 0echo 1.5 <=> 2.5; // -1echo 2.5 <=> 1.5; // 1
 // 字符串echo "a" <=> "a"; // 0echo "a" <=> "b"; // -1echo "b" <=> "a"; // 1
Copy after login

define Define array

In versions prior to PHP7, define cannot define arrays It is now possible, for example,

define('ANIMALS', [
    'dog',
    'cat',
    'bird'
]);

echo ANIMALS[1]; // 输出 "cat"
Copy after login

use method batch import

// PHP 7 之前的代码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 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

Unicode codepoint translation syntax

echo "\u{aa}"; //ªecho "\u{0000aa}";  //ª  echo "\u{9999}"; //香
Copy after login
Anonymous class

<?phpinterface 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;
    }});
Copy after login
PHP 7.1

Nullable types

The types of parameters and return values ​​can now be passed in the type Add a question mark before it to allow it to be empty. When this feature is enabled, the parameters passed in or the result returned by the function are either of the given type or null .

<?phpfunction testReturn(): ?string{
    return &#39;elePHPant&#39;;}var_dump(testReturn()); //string(10) "elePHPant"function testReturn(): ?string{
    return null;}var_dump(testReturn()); //NULLfunction test(?string $name){
    var_dump($name);}test(&#39;elePHPant&#39;); //string(10) "elePHPant"test(null); //NULLtest(); //Uncaught Error: Too few arguments to function test(), 0 passed in...
Copy after login
void

Added a type that returns void, such as

<?phpfunction 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);
Copy after login
Multiple exception capture processing

This function is quite commonly used in daily development

<?php
try {
    // some code
} catch (FirstException | SecondException $e) {  //用 | 来捕获FirstException异常,或者SecondException 异常
  
}
Copy after login
PHP 7.2

PHP7.2 is the least new feature in the PHP7 series


Allow trailing commas in grouped namespaces

For example,

<?phpuse Foo\Bar\{
    Foo,
    Bar,
    Baz,};
Copy after login

Allow overriding of abstract methods

<?phpabstract class A{
    abstract function test(string $s);}abstract class B extends A{
    // overridden - still maintaining contravariance for parameters and covariance for return
    abstract function test($s) : int;}
Copy after login

New object types

<?phpfunction test(object $obj) : object  //这里 可以输入对象{
    return new SplQueue();}test(new StdClass());
Copy after login

PHP 7.3

PHP7.3 There are no big changes at the syntax level.

PHP 7.4

Class attributes support type declaration

Congratulations on PHP taking another step towards strong typing

<?phpclass User {
    public int $id;
    public string $name;}?>
Copy after login
Arrow Functions

Arrow functions provide a shorthand syntax for defining functions using implicit by-value scope binding. It’s similar to the arrow function of JS, but with an fn. A wave of complaints

<?php$factor = 10;$nums = array_map(fn($n) => $n * $factor, [1, 2, 3, 4]);// $nums = array(10, 20, 30, 40);?>
Copy after login

Null merge operator support method######
<?php$array[&#39;key&#39;] ??= computeDefault();// 类似与这个if (!isset($array[&#39;key&#39;])) {
    $array[&#39;key&#39;] = computeDefault();}?>
Copy after login

The above is the detailed content of Summarize the new features of each version of PHP 7.x. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Which versions of PHP7 have introduced new operators Which versions of PHP7 have introduced new operators Mar 03, 2025 pm 04:37 PM

This article details PHP 7's new operators: the null coalescing (??), spaceship (&lt;=&gt;), and null coalescing assignment (??=) operators. These enhance code readability and performance by simplifying null checks and comparisons, indirectl

How to optimize PHP7 code to improve performance How to optimize PHP7 code to improve performance Mar 03, 2025 pm 04:28 PM

This article examines optimizing PHP7 code for performance. It addresses common bottlenecks like inefficient database queries, I/O operations, and memory leaks. Solutions include efficient coding practices, database & caching strategies, asynch

What are the impacts of different versions of PHP7 on memory consumption What are the impacts of different versions of PHP7 on memory consumption Mar 03, 2025 pm 04:35 PM

PHP 7's minor version differences yield subtle memory consumption variations. While newer versions generally improve performance and memory efficiency via Zend Engine and garbage collection optimizations, the impact is application-dependent. Signif

How to Use Sessions Effectively in PHP 7? How to Use Sessions Effectively in PHP 7? Mar 10, 2025 pm 06:20 PM

This article details effective PHP 7 session management, covering core functionalities like session_start(), $_SESSION, session_destroy(), and secure cookie handling. It emphasizes security best practices including HTTPS, session ID regeneration, s

How to Upgrade from PHP 5.6 to PHP 7? How to Upgrade from PHP 5.6 to PHP 7? Mar 10, 2025 pm 06:29 PM

This article details upgrading PHP 5.6 to PHP 7, emphasizing crucial steps like backing up, checking server compatibility, and choosing an upgrade method (package manager, compiling, control panel, or web server configuration). It addresses potentia

What bugs have been fixed in the PHP7 version update What bugs have been fixed in the PHP7 version update Mar 03, 2025 pm 04:36 PM

PHP 7 significantly improved upon previous versions by addressing numerous bugs, enhancing performance, and bolstering security. Key improvements included a rewritten Zend Engine 3, optimized memory management, and refined error handling. While gene

How to Monitor PHP 7 Performance with Tools like New Relic? How to Monitor PHP 7 Performance with Tools like New Relic? Mar 10, 2025 pm 06:28 PM

This article explains how to monitor PHP 7 application performance using New Relic. It details New Relic's setup, key performance indicators (KPIs) like Apdex score and response time, bottleneck identification via transaction traces and error track

What impact does the PHP7 version update have on session processing? What impact does the PHP7 version update have on session processing? Mar 03, 2025 pm 04:31 PM

This article examines session handling in PHP7, highlighting performance improvements stemming from the enhanced Zend Engine. It discusses potential compatibility issues from upgrading and details optimization strategies for security and scalability

See all articles