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!

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

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.

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.

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.


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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version
Recommended: Win version, supports code prompts!

Notepad++7.3.1
Easy-to-use and free code editor

Atom editor mac version download
The most popular open source editor