php7.4 更新特性
PHP 7.4.0 Released!
The PHP development team announces the immediate availability of PHP 7.4.0. This release marks the fourth feature update to the PHP 7 series.
PHP 7.4.0 comes with numerous improvements and new features such as:
Typed Properties
Arrow Functions
Limited Return Type Covariance and Argument Type Contravariance
Unpacking Inside Arrays
Numeric Literal Separator
Weak References
Allow Exceptions from __toString()
Opcache Preloading
Several Deprecations
Extensions Removed from the Core
1.Typed Properties 强类型
Class中预定义变量后, 只能赋值相应的数据类型
All types are supported, with the exception of void and callable:
class User {
public int $id;
public string $name;
}
They are also allowed with the var notation:
var bool $flag;
The same type applies to all properties in a single declaration:
public float $x, $y;
What happens if we make an error on the property type? Consider the following code:
class User {
public int $id;
public string $name;
}
$user = new User;
$user->id = 10;
$user->name = [];
Fatal error:
Fatal error: Uncaught TypeError: Typed property User::$name must be string, array used in /app/types.php:9
2.Arrow Function 箭头函数(简短闭包)
箭头函数为了闭包内只有一行代码的闭包函数提供了更简洁的方式
7.4.0之前
array_map(function (User $user) {
return $user->id;
}, $users)
之后
array_map(fn (User $user) => $user->id, $users)
function cube($n){
return ($n * $n * $n);
}
$a = [1, 2, 3, 4, 5];
$b = array_map('cube', $a);
print_r($b);
之后
$a = [1, 2, 3, 4, 5];
$b = array_map(fn($n) => $n * $n * $n, $a);
print_r($b);
$factor = 10;
$calc = function($num) use($factor){
return $num * $factor;
};
之后
$factor = 10;
$calc = fn($num) => $num * $factor;
3.Limited return type covariance and argument type contravariance 协变返回和逆变参数
子类和父类
协变返回
interface Factory {
function make(): object;
}
class UserFactory implements Factory {
// 将比较泛的 object 类型,具体到 User 类型
function make(): User;
}
逆变参数
interface Concatable {
function concat(Iterator $input);
}
class Collection implements Concatable {
// 将比较具体的 Iterator
参数类型,逆变成接受所有的 iterable
类型
function concat(iterable $input) {/* . . . */}
}
4.Unpacking Inside Arrays 数组内解包
三个点...叫做Spread运算符, 第一个好处是性能
Spread 运算符应该比 array_merge 拥有更好的性能。这不仅仅是 Spread 运算符是一个语法结构,而 array_merge 是一个方法。还是在编译时,优化了高效率的常量数组
$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
var_dump($fruits);
array(5) { [0]=> string(6) "banana" [1]=> string(6) "orange" [2]=> string(5) "apple" [3]=> string(4) "pear" [4]=> string(10) "watermelon" }
RFC 声明我们可以多次扩展同一个数组。而且,我们可以在数组中的任何地方使用扩展运算符语法,因为可以在扩展运算符之前或之后添加普通元素。所以,就像下面代码所示的那样:
$arr1 = [1, 2, 3];
$arr2 = [4, 5, 6];
$arr3 = [...$arr1, ...$arr2];
$arr4 = [...$arr1, ...$arr3, 7, 8, 9];
也可以将函数返回的数组直接合并到另一个数组:
function buildArray(){
return ['red', 'green', 'blue'];
}
$arr1 = [...buildArray(), 'pink', 'violet', 'yellow'];
也可以写成生成器
function generator() {
for ($i = 3; $i <= 5; $i++) {
yield $i;
}
}
$arr1 = [0, 1, 2, ...generator()];
但是我们不允许合并通过引用传递的数组。 考虑以下的例子:
$arr1 = ['red', 'green', 'blue'];
$arr2 = [...&$arr1];
无论如何,如果第一个数组的元素是通过引用存储的,则它们也将通过引用存储在第二个数组中。 这是一个例子:
$arr0 = 'red';
$arr1 = [&$arr0, 'green', 'blue'];
$arr2 = ['white', ...$arr1, 'black'];
上面这个是OK的
5.Numeric Literal Separator
数字字符间可以插入分隔符号
Null Coalescing Assignment Operator
Added with PHP 7, the coalesce operator (??) comes in handy when we need to use a ternary operator in conjunction with isset(). It returns the first operand if it exists and is not NULL. Otherwise, it returns the second operand. Here is an example:
$username = $_GET['user'] ?? ‘nobody';
What this code does is pretty straightforward: it fetches the request parameter and sets a default value if it doesn’t exist. The meaning of that line is clear, but what if we had much longer variable names as in this example from the RFC?
$this->request->data['comments']['user_id'] = $this->request->data['comments']['user_id'] ?? 'value';
In the long run, this code could be a bit difficult to maintain. So, aiming to help developers to write more intuitive code, this RFC proposes the introduction of the null coalescing assignment operator (??=). So, instead of writing the previous code, we could write the following:
$this->request->data['comments']['user_id'] ??= ‘value’;
If the value of the left-hand parameter is null, then the value of the right-hand parameter is used.
Note that, while the coalesce operator is a comparison operator, ??= is an assignment operator.
This proposal has been approved with 37 to 4 votes.
6.Weak References
弱引用使程序员可以保留对对象的引用,不会阻止对象被销毁。
$object = new stdClass;
$weakRef = WeakReference::create($object);
var_dump($weakRef->get());
unset($object);
var_dump($weakRef->get());
The first var_dump prints object(stdClass)#1 (0) {}, while the second var_dump prints NULL, as the referenced object has been destroyed.
object(stdClass)#1 (0) {
}
NULL
7.Allow Exceptions from __toString()
现在允许从 __toString() 引发异常,以往这会导致致命错误,字符串转换中现有的可恢复致命错误已转换为 Error 异常。
foo = $foo;
}
public function __toString() {
return $this->foo;
}
}
$class = new TestClass('Hello');
echo $class;
?>
输出Hello
8.Opcache Preloading 预加载
指定要在服务器启动时期进行编译和缓存的 PHP 脚本文件, 这些文件也可能通过 include 或者 opcache_compile_file() 函数 来预加载其他文件。 所有这些文件中包含的实体,包括函数、类等,在服务器启动的时候就被加载和缓存, 对于用户代码来讲是“开箱可用”的。
php.ini
opcache.preload
On server startup – before any application code is run – we may load a certain set of PHP files into memory – and make their contents “permanently available” to all subsequent requests that will be served by that server. All the functions and classes defined in these files will be available to requests out of the box, exactly like internal entities.
9.Several Deprecations 废弃的
Nested ternary operators without explicit parentheses ¶
Nested ternary operations must explicitly use parentheses to dictate the order of the operations. Previously, when used without parentheses, the left-associativity would not result in the expected behaviour in most cases.
Array and string offset access using curly braces ¶
The array and string offset access syntax using curly braces is deprecated. Use $var[$idx] instead of $var{$idx}.
(real) cast and is_real() function ¶
The (real) cast is deprecated, use (float) instead.
The is_real() function is also deprecated, use is_float() instead.
Unbinding $this when $this is used ¶
Unbinding $this of a non-static closure that uses $this is deprecated.
parent keyword without parent class ¶
Using parent inside a class without a parent is deprecated, and will throw a compile-time error in the future. Currently an error will only be generated if/when the parent is accessed at run-time.
allow_url_include INI option ¶
The allow_url_include ini directive is deprecated. Enabling it will generate a deprecation notice at startup.
Invalid characters in base conversion functions ¶
Passing invalid characters to base_convert(), bindec(), octdec() and hexdec() will now generate a deprecation notice. The result will still be computed as if the invalid characters did not exist. Leading and trailing whitespace, as well as prefixes of type 0x (depending on base) continue to be allowed.
Using array_key_exists() on objects ¶
Using array_key_exists() on objects is deprecated. Instead either isset() or property_exists() should be used.
Magic quotes functions ¶
The get_magic_quotes_gpc() and get_magic_quotes_runtime() functions are deprecated. They always return FALSE.
hebrevc() function ¶
The hebrevc() function is deprecated. It can be replaced with nl2br(hebrev($str)) or, preferably, the use of Unicode RTL support.
convert_cyr_string() function ¶
The convert_cyr_string() function is deprecated. It can be replaced by one of mb_convert_string(), iconv() or UConverter.
money_format() function ¶
The money_format() function is deprecated. It can be replaced by the intl NumberFormatter functionality.
ezmlm_hash() function ¶
The ezmlm_hash() function is deprecated.
restore_include_path() function ¶
The restore_include_path() function is deprecated. It can be replaced by ini_restore('include_path').
Implode with historical parameter order ¶
Passing parameters to implode() in reverse order is deprecated, use implode($glue, $parts) instead of implode($parts, $glue).
COM ¶
Importing type libraries with case-insensitive constant registering has been deprecated.
Filter ¶
FILTER_SANITIZE_MAGIC_QUOTES is deprecated, use FILTER_SANITIZE_ADD_SLASHES instead.
Multibyte String ¶
Passing a non-string pattern to mb_ereg_replace() is deprecated. Currently, non-string patterns are interpreted as ASCII codepoints. In PHP 8, the pattern will be interpreted as a string instead.
Passing the encoding as 3rd parameter to mb_strrpos() is deprecated. Instead pass a 0 offset, and encoding as 4th parameter.
Lightweight Directory Access Protocol ¶
ldap_control_paged_result_response() and ldap_control_paged_result() are deprecated. Pagination controls can be sent along with ldap_search() instead.
Reflection ¶
Calls to ReflectionType::__toString() now generate a deprecation notice. This method has been deprecated in favor of ReflectionNamedType::getName() in the documentation since PHP 7.1, but did not throw a deprecation notice for technical reasons.
The export() methods on all Reflection classes are deprecated. Construct a Reflection object and convert it to string instead:
Socket ¶
The AI_IDN_ALLOW_UNASSIGNED and AI_IDN_USE_STD3_ASCII_RULES flags for socket_addrinfo_lookup() are deprecated, due to an upstream deprecation in glibc.
10.Extensions Removed from the Core
These extensions have been moved to PECL and are no longer part of the PHP distribution. The PECL package versions of these extensions will be created according to user demand.
- Firebird/Interbase - access to an InterBase and/or Firebird based database is still available with the PDO Firebird driver.
- Recode
- WDDX
更多详情可见RFC文档 https://wiki.php.net/rfc
php7.4 更新特性的更多相关文章
- php7.0 和 php7.1新特性
PHP7.1 新特性 1.可为空(Nullable)类型 类型现在允许为空,当启用这个特性时,传入的参数或者函数返回的结果要么是给定的类型,要么是 null .可以通过在类型前面加上一个问号来使之成为 ...
- 浅谈PHP7的新特性
我以前用过的php的最高版本是php5.6.在换新工作之后,公司使用的是PHP7.据说PHP7的性能比之前提高很多.下面整理下php7的新特性.力求简单了解.不做深入研究. 1.变量类型声明 函数的参 ...
- php5.6.x到php7.0.x特性
php5.6.x到php7.0.x特性 1.标量类型声明 字符串(string), 整数 (int), 浮点数 (float), 布尔值 (bool),callable,array,self,Clas ...
- git与eclipse集成之更新特性分支代码到个人特性分支
1.1. 更新特性分支代码到个人特性分支 在基于特性分支开发的过程中,存在多人向特性分支提交代码的情况,开发者需要关注特性分支代码与个人分支代码保持同步,否则可能导致提交代码冲突. 具体代码同步步骤: ...
- 《PHP7底层设计与源码实现》学习笔记1——PHP7的新特性和源码结构
<PHP7底层设计与源码实现>一书的作者陈雷亲自给我们授课,大佬现身!但也因此深感自己基础薄弱,遂买了此书.希望看完这本书后,能让我对PHP7底层的认识更上一层楼.好了,言归正传,本书共1 ...
- [转+自]关于PHP7的新特性(涉及取反和disabled_functions绕过)
PHP7和PHP5上的安全区别 preg_replace()不再支持/e修饰符 利用\e修饰符执行代码的后门大家也用了不少了,具体看官方的这段描述: 如果设置了这个被弃用的修饰符, preg_repl ...
- PHP7.x新特性
1.太空船操作符太空船操作符用于比较两个表达式. 当$a小于. 等于或大于$b时它分别返回-1. 0或1. // Integers echo 1 <=> 1; // 0 echo 1 &l ...
- php7的新特性
新增操作符1.??$username = $_GET['user'] ?? '';$username = isset($_GET['user']) ? $_GET['user'] : 'nobody' ...
- PHP7.1新特性一览
PHP7.0的性能是PHP5.6的两倍 http://www.phpchina.com/article-40237-1.html 可空类型 list 的方括号简写 void 返回类型 类常量属性设定 ...
随机推荐
- 20180520模拟赛T3——chess
[问题描述] 小美很喜欢下象棋. 而且她特别喜欢象棋中的马. 她觉得马的跳跃方式很独特.(以日字格的方式跳跃) 小芳给了小美一张很大的棋盘,这个棋盘是一个无穷的笛卡尔坐标. 一开始\(time=0\) ...
- HDU6592 Beauty Of Unimodal Sequence
Beauty Of Unimodal Sequence 给一个序列,在满足单调递增或者单调递减或者先增后减的最长子序列集合里找到下标字典序最大以及最小的两个子序列,输出这两个子序列里元素的下标. n≤ ...
- Tomcat热部署和热加载
1.热部署与热加载 在应用运行的时候升级软件,无需重新启动的方式有两种,热部署和热加载.它们之间的区别是: (1).部署方式: 热部署在服务器运行时重新部署项目.热加载在运行时重新加载class. ( ...
- python基础语法1 用户交互,基本数据类型,格式化输出,运算符
与用户交互: 输入: python2: input一定要声明你输入的类型 >>> input(">>:") >>:sean Traceba ...
- ajax请求数据时,get和post的区别
发送机制 1.get请求会将参数跟在URL后面进行参数传递,而post请求则是作为http消息的实体内容发送给web服务器: 2.get提交的数据限制是1024字节,这种显示是来自特定浏览器和服务器对 ...
- Linux中tune2fs命令的-o选项
debug 启用此文件系统的调试代码. bsdgroups 在创建新文件时模拟BSD行为:它们将使用创建它们的目录.标准系统V的行为是默认情况下,新创建的文件采用当前进程的fsgid,除非目录设置了s ...
- dotnetcore docker 简单运行
今天试用了下mac 版本的dotnetcore sdk,发现还是很方便的,同时官方的容器运行方式,相对小了好多 同时使用多阶段构建的方式运行dotnetcore 安装sdk 下载地址: https:/ ...
- CSS的初步学习
CSS的作用: 被用来格式化HTML文档 插入样式的方法: 外部样式表 目的: 适合格式化多个页面,减少工程量. 用法: 每个html页面使用标签(在页面头部)链接到样式表中,代码如下: <he ...
- x64汇编第二讲,复习x86汇编指令格式,学习x64指令格式
目录 x64汇编第二讲,复习x86汇编指令格式,学习x64指令格式 一丶x86指令复习. 1.1什么是x86指令. 1.2 x86与x64下的通用寄存器 1.3 OpCode 1.4 7种寻址方式 二 ...
- nginx 访问控制之 http_referer
在rewrite时,曾经用过该变量,当时实现了防盗链功能. 其实基于该变量,我们也可以做一些特殊的需求. 示例: 背景:网站被黑挂马,搜索引擎收录的网页是有问题的,当通过搜索引擎点击到网站时,却显示一 ...