Backend Development
PHP Tutorial
What are the new features of PHP7? Compilation of common new features of php7
What 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['a']) ? $_GET['a'] : 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:6After 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, '3', 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!
Hot AI Tools
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undress AI Tool
Undress images for free
Clothoff.io
AI clothes remover
AI Hentai Generator
Generate AI Hentai for free.
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
1384
52
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
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
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 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 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
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 to automatically set permissions of unixsocket after system restart?
Mar 31, 2025 pm 11:54 PM
How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...
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.


