New features added in PHP 7
This article mainly introduces the newly added features of PHP 7, which has a certain reference value. Now I share it with everyone. Friends in need can refer to this
Scalar type declaration
PHP 7 The formal parameter type declaration of functions in can now be scalar. In PHP 5 it can only be a class name, interface, array or callable (PHP5.4, that is, it can be a function, including anonymous function ), now you can also use string, int, float and bool are gone.
<?php // 强制模式 function sumOfInts(int...$ints) { return array_sum($ints); } var_dump(sumOfInts(2,'3',4.1));
The above example will output:
int(9)
It should be noted that the strict mode problem mentioned above also applies here: in forced mode (default, which is forced type conversion), there will still be errors that do not meet expectations. The parameters are forced to type conversion, and in strict mode, a fatal error of TypeError will be triggered.
##Return value type declaration
PHP 7 Added support for return type declarations. Similar to the parameter type declaration, the return type declaration specifies the type of function return value. The available types are the same as those available in the parameter declaration.
<?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]));
The above example will output:
Array ( [0]=>6 [1]=>15 [2]=>24 )
NULL Coalescing operator
Due to the large number of simultaneous uses of ternary expressions and isset in daily use () situation, NULL The merging operator makes the variable exist and the value is not NULL, It will return its own value, otherwise it will return its second operand.
Examples are as follows:
<?php // 如果 $_GET['user'] 不存在返回 'nobody',否则返回 $_GET['user'] 的值 $username = $_GET['user']??'nobody'; // 类似的三元运算符 $username = isset($_GET['user'])? $_GET['user']:'nobody'; ?>
##Spaceship operator (combined comparison operator)
The spaceship operator is used to compare two expressions. It returns-1 when $a is greater than, equal to or less than $b respectively. , 0 or 1.
Examples are as follows:<?php
// 整型
echo 1<=>1;// 0
echo 1<=>2;// -1
echo 2<=>1;// 1
// 浮点型
echo 1.5<=>1.5;// 0
echo 1.5<=>2.5;// -1
echo 2.5<=>1.5;// 1
// 字符串
echo "a"<=>"a";// 0
echo "a"<=>"b";// -1
echo "b"<=>"a";// 1
?>
##Through
define() Define constant array##The example is as follows:
<?php define('ANIMALS',[ 'dog', 'cat', 'bird' ]); echo ANIMALS[1];// 输出 "cat" ?>
##Anonymous classes
now supports passing new class
To instantiate an anonymous class, the example is as follows:
<?php interfaceLogger{ publicfunction log(string $msg); } classApplication{ private $logger; publicfunction getLogger():Logger{ return $this->logger; } publicfunction setLogger(Logger $logger){ $this->logger = $logger; } } $app =newApplication; $app->setLogger(newclassimplementsLogger{ publicfunction log(string $msg){ echo $msg; } }); var_dump($app->getLogger()); ?>
以上实例会输出:
object(class@anonymous)#2(0){ }
Unicode codepoint 转译语法
这接受一个以16进制形式的 Unicodecodepoint,并打印出一个双引号或heredoc包围的 UTF-8 编码格式的字符串。可以接受任何有效的 codepoint,并且开头的 0 是可以省略的。
echo "\u{aa}"; echo "\u{0000aa}"; echo "\u{9999}";
以上实例会输出:
ª ª(same as before but with optional leading 0's)
香
Closure::call()
Closure::call() 现在有着更好的性能,简短干练的暂时绑定一个方法到对象上闭包并调用它。
<?php class A {private $x =1;} // Pre PHP7 代码 $getXCB =function(){return $this->x;}; $getX = $getXCB->bindTo(new A,'A');// intermediate closure echo $getX(); // PHP 7+ 代码 $getX =function(){return $this->x;}; echo $getX->call(new A);
以上实例会输出:
1 1
为unserialize()提供过滤
这个特性旨在提供更安全的方式解包不可靠的数据。它通过白名单的方式来防止潜在的代码注入。
<?php // 转换对象为 __PHP_Incomplete_Class 对象 $data = unserialize($foo,["allowed_classes"=>false]); // 转换对象为 __PHP_Incomplete_Class 对象,除了 MyClass 和 MyClass2 $data = unserialize($foo,["allowed_classes"=>["MyClass","MyClass2"]); // 默认接受所有类 $data = unserialize($foo,["allowed_classes"=>true]);
IntlChar
新增加的 IntlChar 类旨在暴露出更多的 ICU 功能。这个类自身定义了许多静态方法用于操作多字符集的 unicode 字符。
<?php printf('%x',IntlChar::CODEPOINT_MAX); echo IntlChar::charName('@'); var_dump(IntlChar::ispunct('!'));
以上实例会输出:
10ffff COMMERCIAL AT bool(true)
若要使用此类,请先安装Intl扩展
预期
预期是向后兼用并增强之前的 assert() 的方法。它使得在生产环境中启用断言为零成本,并且提供当断言失败时抛出特定异常的能力。
<?php ini_set('assert.exception',1); classCustomErrorextendsAssertionError{} assert(false,newCustomError('Someerror message')); ?>
以上实例会输出:
Fatalerror:Uncaught CustomError:Some error message
use 加强
从同一 namespace 导入的类、函数和常量现在可以通过单个 use 语句一次性导入了。
<?php // PHP 7 之前版本用法 use some\namespace\ClassA; use some\namespace\ClassB; use some\namespace\ClassC as C; usefunction some\namespace\fn_a; usefunction some\namespace\fn_b; usefunction some\namespace\fn_c; useconst some\namespace\ConstA; useconst some\namespace\ConstB; useconst some\namespace\ConstC; // PHP 7+ 用法 use some\namespace\{ClassA,ClassB,ClassCas C}; usefunction some\namespace\{fn_a, fn_b, fn_c}; useconst some\namespace\{ConstA,ConstB,ConstC}; ?>
Generator 加强
增强了Generator的功能,这个可以实现很多先进的特性
<?php <?php function gen() { yield1; yield2; yieldfrom gen2(); } function gen2() { yield3; yield4; } foreach(gen()as $val) { echo $val, PHP_EOL; } ?>
以上实例会输出:
1 2 3 4
整除
新增了整除函数 intp(),使用实例:
<?php var_dump(intp(10,3)); ?>
以上实例会输出:
int(3)
相关推荐:
The above is the detailed content of New features added in PHP 7. 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



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

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

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

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

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,

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

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