Home Backend Development PHP Tutorial New features added in PHP 7

New features added in PHP 7

May 03, 2018 pm 02:08 PM
php Increase characteristic

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,&#39;3&#39;,4.1));
Copy after login

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]));
Copy after login

The above example will output:

Array
(
    [0]=>6
    [1]=>15
    [2]=>24
)
Copy after login


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[&#39;user&#39;] 不存在返回 &#39;nobody&#39;,否则返回 $_GET[&#39;user&#39;] 的值
$username = $_GET[&#39;user&#39;]??&#39;nobody&#39;;
// 类似的三元运算符
$username = isset($_GET[&#39;user&#39;])? $_GET[&#39;user&#39;]:&#39;nobody&#39;;
?>
Copy after login


##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
?>
Copy after login


##Through

define() Define constant array##The example is as follows:

<?php
define(&#39;ANIMALS&#39;,[
    &#39;dog&#39;,
    &#39;cat&#39;,
    &#39;bird&#39;
]);
 
echo ANIMALS[1];// 输出 "cat"
?>
Copy after login


##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());
?>
Copy after login

以上实例会输出:

object(class@anonymous)#2(0){
}
Copy after login


Unicode codepoint 转译语法

这接受一个以16进制形式的 Unicodecodepoint,并打印出一个双引号或heredoc包围的 UTF-8 编码格式的字符串。可以接受任何有效的 codepoint,并且开头的 0 是可以省略的。

echo "\u{aa}";
echo "\u{0000aa}";
echo "\u{9999}";
Copy after login

以上实例会输出:

ª
ª(same as before but with optional leading 0&#39;s)
Copy after login
Copy after login


Closure::call()

Closure::call() 现在有着更好的性能,简短干练的暂时绑定一个方法到对象上闭包并调用它。

<?php
class A {private $x =1;}
 
// Pre PHP7 代码
$getXCB =function(){return $this->x;};
$getX = $getXCB->bindTo(new A,&#39;A&#39;);// intermediate closure
echo $getX();
 
// PHP 7+ 代码
$getX =function(){return $this->x;};
echo $getX->call(new A);
Copy after login

以上实例会输出:

1
1
Copy after login


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]);
Copy after login


IntlChar

新增加的 IntlChar 类旨在暴露出更多的 ICU 功能。这个类自身定义了许多静态方法用于操作多字符集的 unicode 字符。

<?php
printf(&#39;%x&#39;,IntlChar::CODEPOINT_MAX);
echo IntlChar::charName(&#39;@&#39;);
var_dump(IntlChar::ispunct(&#39;!&#39;));
Copy after login

以上实例会输出:

10ffff
COMMERCIAL AT
bool(true)
Copy after login

若要使用此类,请先安装Intl扩展


预期

预期是向后兼用并增强之前的 assert() 的方法。它使得在生产环境中启用断言为零成本,并且提供当断言失败时抛出特定异常的能力。

<?php
ini_set(&#39;assert.exception&#39;,1);
 
classCustomErrorextendsAssertionError{}
 
assert(false,newCustomError(&#39;Someerror message&#39;));
?>
Copy after login

以上实例会输出:

Fatalerror:Uncaught CustomError:Some error message
Copy after login


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};
?>
Copy after login



Generator 加强

增强了Generator的功能,这个可以实现很多先进的特性

<?php
<?php
 
function gen()
{
    yield1;
    yield2;
 
    yieldfrom gen2();
}
 
function gen2()
{
    yield3;
    yield4;
}
 
foreach(gen()as $val)
{
    echo $val, PHP_EOL;
}
 
?>
Copy after login

以上实例会输出:

1
2
3
4
Copy after login


整除

新增了整除函数 intp(),使用实例:

<?php
var_dump(intp(10,3));
?>
Copy after login

以上实例会输出:

int(3)
Copy after login

相关推荐:

php 5.4中新增加对session状态判断的功能

 

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!

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)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months 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)

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

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

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

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