search
HomeBackend DevelopmentPHP TutorialWhat are the new features of PHP7? Compilation of common new features of php7

In PHP7, due to the modification of most of the code of the underlying engine and the improvement of PHP performance through various methods, some new syntax has also been added to PHP7. The use of these syntaxes can also help improve performance. Let's sort out the new features commonly used in php7.

1. ?? Operator (NULL merge operator)

I put this first because I think it is very useful. Usage:

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

It is equivalent to:

<?php $a = isset($_GET[&#39;a&#39;]) ? $_GET[&#39;a&#39;] : 1;

We know that the ternary operator can be used like this:

$a ?: 1

But this is based on $a already defined On the premise. The new ?? operator can simplify judgment.

2. Function return value type declaration

Examples provided by official documents (note that the side length parameter syntax of ... is in PHP 5.6 or above Only available in version):

<?php function arraysSum(array ...$arrays): array
{
    return array_map(function(array $array): int {
        return array_sum($array);
    }, $arrays);
}

print_r(arraysSum([1,2,3], [4,5,6], [7,8,9]));

From this example, we can see that now functions (including anonymous functions) can specify the type of return value.

The way this statement is written is somewhat similar to swift:

func sayHello(personName: String) -> String {
    let greeting = "Hello, " + personName + "!"
    return greeting
}

This feature can help us avoid some problems caused by PHP's implicit type conversion. Thinking about the expected results before defining a function can avoid unnecessary mistakes.

But there is also a feature that needs attention here. PHP 7 adds a declare directive: strict_types, which uses strict mode.

When using return value type declaration, if it is not declared in strict mode, and if the return value is not the expected type, PHP will still perform cast type conversion on it. But if it is strict mode, a Fatal error of TypeError will be issued.

Forced mode:

<?php function foo($a) : int
{
    return $a;
}

foo(1.0);

The above code can be executed normally, and the foo function returns int 1 without any errors.

Strict mode:

<?php declare(strict_types=1);

function foo($a) : int
{
    return $a;
}

foo(1.0);
# PHP Fatal error:  Uncaught TypeError: Return value of foo() must be of the type integer, float returned in test.php:6

After the declaration, a fatal error will be triggered.

Is it similar to the strict mode of js?

3. Scalar type declaration

The formal parameter type declaration of a function in PHP 7 can now be a scalar. In PHP 5, it can only be a class name, interface, array or callable (PHP 5.4, that is, it can be a function, including anonymous functions). Now you can also use string, int, float and bool are gone.

Official example:

<?php // Coercive mode
function sumOfInts(int ...$ints)
{
    return array_sum($ints);
}

var_dump(sumOfInts(2, &#39;3&#39;, 4.1));

It should be noted that the strict mode problem mentioned above also applies here: in forced mode (default, both forced type conversion), there will still be errors that do not conform to the The expected parameters are cast to type, and a TypeError fatal error is triggered in strict mode.

4. Use batch declaration

In PHP 7, use can declare multiple classes or functions or const in one sentence:

<?php 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};

But You still have to write out the name of each class or function or const (there is no from some import * method like python).

The question you need to pay attention to is: if you are using a framework based on composer and PSR-4, can this writing method successfully load class files? In fact, it is possible. The autoloading method registered by composer searches the location according to the namespace of the class when the class is called. This way of writing has no effect on it.

In addition to the above new features, let me briefly mention a few:

PHP 5.3 started to have anonymous functions, and now there are anonymous classes;

define can now be defined Constant array;

Closure (Closure) adds a call method;

The generator (or iterator is more appropriately called) can have a final return value (return), or it can pass yield New syntax for from into another generator (generator delegate).

The two new features of generators (return and yield from) can be combined. You can test the specific appearance by yourself. PHP 7 is now at RC5 and the final version should be coming soon.

Recommended related articles:

PHP7 New Features Introduction

A brief talk about the major new features of php7, a brief talk about php7

[Translation]Introduction to PHP7: New and Removed Features

The above is the detailed content of What are the new features of PHP7? Compilation of common new features of php7. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools