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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM