search
HomeBackend DevelopmentPHP TutorialNew features added in PHP 7

New features added in PHP 7

May 03, 2018 pm 02:08 PM
phpIncreasecharacteristic

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

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[&#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;;
?>


##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(&#39;ANIMALS&#39;,[
    &#39;dog&#39;,
    &#39;cat&#39;,
    &#39;bird&#39;
]);
 
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&#39;s)


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

以上实例会输出:

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(&#39;%x&#39;,IntlChar::CODEPOINT_MAX);
echo IntlChar::charName(&#39;@&#39;);
var_dump(IntlChar::ispunct(&#39;!&#39;));

以上实例会输出:

10ffff
COMMERCIAL AT
bool(true)

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


预期

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

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

以上实例会输出:

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)

相关推荐:

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
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
Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

Explain Fibers in PHP 8.1 for concurrency.Explain Fibers in PHP 8.1 for concurrency.Apr 12, 2025 am 12:05 AM

Fibers was introduced in PHP8.1, improving concurrent processing capabilities. 1) Fibers is a lightweight concurrency model similar to coroutines. 2) They allow developers to manually control the execution flow of tasks and are suitable for handling I/O-intensive tasks. 3) Using Fibers can write more efficient and responsive code.

The PHP Community: Resources, Support, and DevelopmentThe PHP Community: Resources, Support, and DevelopmentApr 12, 2025 am 12:04 AM

The PHP community provides rich resources and support to help developers grow. 1) Resources include official documentation, tutorials, blogs and open source projects such as Laravel and Symfony. 2) Support can be obtained through StackOverflow, Reddit and Slack channels. 3) Development trends can be learned by following RFC. 4) Integration into the community can be achieved through active participation, contribution to code and learning sharing.

PHP vs. Python: Understanding the DifferencesPHP vs. Python: Understanding the DifferencesApr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: Is It Dying or Simply Adapting?PHP: Is It Dying or Simply Adapting?Apr 11, 2025 am 12:13 AM

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

The Future of PHP: Adaptations and InnovationsThe Future of PHP: Adaptations and InnovationsApr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

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

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version