Home >Backend Development >PHP Tutorial >PHP7.0 version notes, php7.0 notes_PHP tutorial
The new version of PHP7.0 not only greatly improves performance but also changes a lot in terms of language features. Please see below for detailed explanation :
1. Backward-incompatible changes
Language changes
Changes in variable handling
Indirect variable, property, and method references are now interpreted with left-to-right semantics. Some examples:
$$foo['bar']['baz'] // 解释做 ($$foo)['bar']['baz'] $foo->$bar['baz'] // 解释做 ($foo->$bar)['baz'] $foo->$bar['baz']() // 解释做 ($foo->$bar)['baz']() Foo::$bar['baz']() // 解释做 (Foo::$bar)['baz']()
To restore the previous behavior, explicitly add braces:
${$foo['bar']['baz']} $foo->{$bar['baz']} $foo->{$bar['baz']}() Foo::{$bar['baz']}()
Global keywords now only accept simple variables. Like before
Copy code The code is as follows:
global $$foo->bar;
Now the following writing method is required:
Copy code The code is as follows:
global ${$foo->bar};
Placing parentheses around a variable or function call no longer has any effect. For example, in the following code, the function call result is passed to a function by reference
function getArray() { return [1, 2, 3]; } $last = array_pop(getArray()); // Strict Standards: 只有变量可以用引用方式传递 $last = array_pop((getArray()));
// Strict Standards: Only variables can be passed by reference
Now a strict standard error is thrown regardless of whether parentheses are used. Previously there was no prompt in the second calling method.
Array elements or object properties are automatically created in reference order and the resulting order will now be different. For example:
$array = []; $array["a"] =& $array["b"]; $array["b"] = 1; var_dump($array); 现在结果是 ["a" => 1, "b" => 1],而以前的结果是 ["b" => 1, "a" => 1]
Related RFCs:
https://wiki.php.net/rfc/uniform_variable_syntax
https://wiki.php.net/rfc/abstract_syntax_tree
Changes in list()
list() no longer assigns values in reverse order, for example:
Copy code The code is as follows:
list($array[], $array[], $array[]) = [1, 2, 3];
var_dump($array);
Now the result is $array == [1, 2, 3] instead of [3, 2, 1]. Note that only the order of assignment has changed, but the assignment is still the same (LCTT translation: that is, the previous list() behavior was to assign values one by one starting from the following variables, so that the above usage will produce a result like [3,2,1] .). For example, common usage like the following
Copy code The code is as follows:
list($a, $b, $c) = [1, 2, 3];
// $a = 1; $b = 2; $c = 3;
Current behavior is still maintained.
Assignment to an empty list() is no longer allowed. The following are all invalid:
list() = $a; list(,,) = $a; list($x, list(), $y) = $a; list() 不再支持对字符串的拆分(以前也只在某些情况下支持)
The following code:
Copy code The code is as follows:
$string = "xy";
list($x, $y) = $string;
The result now is: $x == null and $y == null (without prompt), whereas before the result was: $x == "x" and $y == "y" .
Additionally, list() can now always handle objects that implement ArrayAccess, for example:
Copy code The code is as follows:
list($a, $b) = (object) new ArrayObject([0, 1]);
The result now is: $a == 0 and $b == 1. Previously $a and $b were both null.
Related RFC:
https://wiki.php.net/rfc/abstract_syntax_tree#changes_to_list
https://wiki.php.net/rfc/fix_list_behavior_inconsistency
Changes to foreach
foreach() iteration no longer affects the internal array pointer, which can be accessed through current()/next() and other series of functions. For example:
Copy code The code is as follows:
$array = [0, 1, 2];
foreach ($array as &$val) {
var_dump(current($array));
}
It will now point to the value int(0) three times. Previous output was int(1), int(2), and bool(false).
When iterating an array by value, foreach always operates on a copy of the array, and any operations on the array during iteration will not affect the iteration behavior. For example:
Copy code The code is as follows:
$array = [0, 1, 2];
$ref =& $array; // Necessary to trigger the old behavior
foreach ($array as $val) {
var_dump($val);
unset($array[1]);
}
All three elements (0 1 2) will now be printed, whereas previously the second element 1 would be skipped (0 2).
When iterating over an array by reference, modifications to the array will continue to affect the iteration. However, PHP now maintains better positioning within arrays when using numbers as keys. For example, adding array elements during by-reference iteration:
Copy code The code is as follows:
$array = [0];
foreach ($array as &$val) {
var_dump($val);
$array[1] = 1;
}
Iteration now correctly adds elements. The output of the above code is "int(0) int(1)", whereas before it was just "int(0)".
Iteration by value or by reference over a normal (non-traversable) object behaves like iteration by reference over an array. This is in line with previous behavior, except for improvements to more precise location management as mentioned in the previous point.
The behavior of iteration over traversable objects remains unchanged.
Related RFC: https://wiki.php.net/rfc/php7_foreach
Changes in parameter handling
Two function parameters with the same name cannot be defined. For example, the following method will trigger a compile-time error:
复制代码 代码如下:
public function foo($a, $b, $unused, $unused) {
// ...
}
如上的代码应该修改使用不同的参数名,如:
复制代码 代码如下:
public function foo($a, $b, $unused1, $unused2) {
// ...
}
func_get_arg() 和 func_get_args() 函数不再返回传递给参数的原始值,而是返回其当前值(也许会被修改)。例如:
复制代码 代码如下:
function foo($x) {
$x++;
var_dump(func_get_arg(0));
}
foo(1);
将会打印 "2" 而不是 "1"。代码应该改成仅在调用 func_get_arg(s) 后进行修改操作。
复制代码 代码如下:
function foo($x) {
var_dump(func_get_arg(0));
$x++;
}
或者应该避免修改参数:
复制代码 代码如下:
function foo($x) {
$newX = $x + 1;
var_dump(func_get_arg(0));
}
类似的,异常回溯也不再显示传递给函数的原始值,而是修改后的值。例如:
复制代码 代码如下:
function foo($x) {
$x = 42;
throw new Exception;
}
foo("string");
现在堆栈跟踪的结果是:
复制代码 代码如下:
Stack trace:
#0 file.php(4): foo(42)
#1 {main}
而以前是:
复制代码 代码如下:
Stack trace:
#0 file.php(4): foo('string')
#1 {main}
这并不会影响到你的代码的运行时行为,值得注意的是在调试时会有所不同。
同样的限制也会影响到 debug_backtrace() 及其它检查函数参数的函数。
相关 RFC: https://wiki.php.net/phpng
整数处理的变化
无效的八进制表示(包含大于7的数字)现在会产生编译错误。例如,下列代码不再有效:
$i = 0781; // 8 不是一个有效的八进制数字!
以前,无效的数字(以及无效数字后的任何数字)会简单的忽略。以前如上 $i 的值是 7,因为后两位数字会被悄悄丢弃。
二进制以负数镜像位移现在会抛出一个算术错误:
复制代码 代码如下:
var_dump(1 >> -1);
// ArithmeticError: 以负数进行位移
向左位移的位数超出了整型宽度时,结果总是 0。
复制代码 代码如下:
var_dump(1 09bbd6d71772184a40d0defa55f86c39> 64); // int(0)
var_dump(-1 >> 64); // int(-1)
相关 RFC: https://wiki.php.net/rfc/integer_semantics
字符串处理的变化
包含十六进制数字的字符串不会再被当做数字,也不会被特殊处理。参见例子中的新行为:
复制代码 代码如下:
var_dump("0x123" == "291"); // bool(false) (以前是 true)
var_dump(is_numeric("0x123")); // bool(false) (以前是 true)
var_dump("0xe" + "0x1"); // int(0) (以前是 16)
var_dump(substr("foo", "0x1")); // string(3) "foo" (以前是 "oo")
// 注意:遇到了一个非正常格式的数字
filter_var() 可以用来检查一个字符串是否包含了十六进制数字,或这个字符串是否能转换为整数:
$str = "0xffff"; $int = filter_var($str, FILTER_VALIDATE_INT, FILTER_FLAG_ALLOW_HEX); if (false === $int) { throw new Exception("Invalid integer!"); } var_dump($int); // int(65535)
由于给双引号字符串和 HERE 文档增加了 Unicode 码点转义格式(Unicode Codepoint Escape Syntax), 所以带有无效序列的 "\u{" 现在会造成错误:
$str = "\u{xyz}"; // 致命错误:无效的 UTF-8 码点转义序列
要避免这种情况,需要转义开头的反斜杠:
$str = "\\u{xyz}"; // 正确
不过,不跟随 { 的 "\u" 不受影响。如下代码不会生成错误,和前面的一样工作:
$str = "\u202e"; // 正确
相关 RFC:
https://wiki.php.net/rfc/remove_hex_support_in_numeric_strings
https://wiki.php.net/rfc/unicode_escape
错误处理的变化
现在有两个异常类: Exception 和 Error 。这两个类都实现了一个新接口: Throwable 。在异常处理代码中的类型指示也许需要修改来处理这种情况。
一些致命错误和可恢复的致命错误现在改为抛出一个 Error 。由于 Error 是一个独立于 Exception 的类,这些异常不会被已有的 try/catch 块捕获。
可恢复的致命错误被转换为一个异常,所以它们不能在错误处理里面悄悄的忽略。部分情况下,类型指示失败不再能忽略。
解析错误现在会生成一个 Error 扩展的 ParseError 。除了以前的基于返回值 / errorgetlast() 的处理,对某些可能无效的代码的 eval() 的错误处理应该改为捕获 ParseError 。
内部类的构造函数在失败时总是会抛出一个异常。以前一些构造函数会返回 NULL 或一个不可用的对象。
一些 E_STRICT 提示的错误级别改变了。
相关 RFC:
https://wiki.php.net/rfc/engine_exceptions_for_php7
https://wiki.php.net/rfc/throwable-interface
https://wiki.php.net/rfc/internal_constructor_behaviour
https://wiki.php.net/rfc/reclassify_e_strict
其它的语言变化
静态调用一个不兼容的 $this 上下文的非静态调用的做法不再支持。这种情况下,$this 是没有定义的,但是对它的调用是允许的,并带有一个废弃提示。例子:
class A { public function test() { var_dump($this); } } // 注意:没有从类 A 进行扩展 class B { public function callNonStaticMethodOfA() { A::test(); } } (new B)->callNonStaticMethodOfA();
// 废弃:非静态方法 A::test() 不应该被静态调用
// 提示:未定义的变量 $this
NULL
注意,这仅出现在来自不兼容上下文的调用上。如果类 B 扩展自类 A ,调用会被允许,没有任何提示。
不能使用下列类名、接口名和特殊名(大小写敏感):
bool
int
float
string
null
false
true
这用于 class/interface/trait 声明、 class_alias() 和 use 语句中。
此外,下列类名、接口名和特殊名保留做将来使用,但是使用时尚不会抛出错误:
resource
object
mixed
numeric
yield 语句结构当用在一个表达式上下文时,不再要求括号。它现在是一个优先级在 “print” 和 “=>” 之间的右结合操作符。在某些情况下这会导致不同的行为,例如:
echo yield -1;
// 以前被解释如下
echo (yield) - 1;
// 现在被解释如下
echo yield (-1);
yield $foo or die;
// 以前被解释如下
yield ($foo or die);
// 现在被解释如下
(yield $foo) or die;
这种情况可以通过增加括号来解决。
移除了 ASP (fa95ae8e6d3672ec0d43a8d80f1a3206) 标签。
RFC: https://wiki.php.net/rfc/remove_alternative_php_tags
不支持以引用的方式对 new 的结果赋值。
不支持对一个来自非兼容的 $this 上下文的非静态方法的域内调用。细节参见: https://wiki.php.net/rfc/incompat_ctx 。
不支持 ini 文件中的 # 风格的备注。使用 ; 风格的备注替代。
$HTTP_RAW_POST_DATA 不再可用,使用 php://input 流替代。
标准库的变化
call_user_method() 和 call_user_method_array() 不再存在。
在一个输出缓冲区被创建在输出缓冲处理器里时, ob_start() 不再发出 E_ERROR,而是 E_RECOVERABLE_ERROR。
改进的 zend_qsort (使用 hybrid 排序算法)性能更好,并改名为 zend_sort。
增加静态排序算法 zend_insert_sort。
移除 fpm-fcgi 的 dl() 函数。
setcookie() 如果 cookie 名为空会触发一个 WARNING ,而不是发出一个空的 set-cookie 头。
其它
Curl:
去除对禁用 CURLOPT_SAFE_UPLOAD 选项的支持。所有的 curl 文件上载必须使用 curl_file / CURLFile API。
Date:
从 mktime() 和 gmmktime() 中移除 $is_dst 参数
DBA
如果键也没有出现在 inifile 处理器中,dba_delete() 现在会返回 false。
GMP
现在要求 libgmp 版本 4.2 或更新。
gmp_setbit() 和 gmp_clrbit() 对于负指标返回 FALSE,和其它的 GMP 函数一致。
Intl:
移除废弃的别名 datefmt_set_timezone_id() 和 IntlDateFormatter::setTimeZoneID()。替代使用 datefmt_set_timezone() 和 IntlDateFormatter::setTimeZone()。
libxml:
增加 LIBXML_BIGLINES 解析器选项。从 libxml 2.9.0 开始可用,并增加了在错误报告中行号大于 16 位的支持。
Mcrypt
移除等同于 mcrypt_generic_deinit() 的废弃别名 mcrypt_generic_end()。
移除废弃的 mcrypt_ecb()、 mcrypt_cbc()、 mcrypt_cfb() 和 mcrypt_ofb() 函数,它们等同于使用 MCRYPT_MODE_* 标志的 mcrypt_encrypt() 和 mcrypt_decrypt() 。
Session
session_start() accepts all INI settings as an array. For example, ['cache_limiter'=>'private'] sets session.cache_limiter=private . 'read_and_close' is also supported to close session data immediately after reading the data.
The session save processor accepts validate_sid() and update_timestamp() to verify the existence of the session ID and update the session timestamp. Continued compatibility with legacy user-defined session save handlers.
Added SessionUpdateTimestampHandlerInterface. validateSid(), updateTimestamp() are defined in the interface.
The INI setting of session.lazy_write (On by default) supports writing only when session data is updated.
Opcache
Remove opcache.load_comments configuration statement. In-file notes are now loaded at no cost and are always enabled.
OpenSSL:
Removed "rsa_key_size" SSL context option to automatically set the appropriate size given the negotiated encryption algorithm.
Removed "CN_match" and "SNI_server_name" SSL context options. Use autodetection or the "peer_name" option instead.
PCRE:
Remove support for /e (PREG_REPLACE_EVAL) modifier, use preg_replace_callback() instead.
PDO_pgsql:
Removed PGSQL_ATTR_DISABLE_NATIVE_PREPARED_STATEMENT attribute, equivalent to ATTR_EMULATE_PREPARES.
Standard:
Remove string category support in setlocale(). Use LC_* constants instead. instead.
Removed set_magic_quotes_runtime() and its alias magic_quotes_runtime().
JSON:
Reject RFC 7159 incompatible number format in json_decode - top level (07, 0xff, .1, -.1) and all levels ([1.], [1.e1])
Calling json_decode with one argument is equivalent to calling it with an empty PHP string or value, and the result of conversion to an empty string (NULL, FALSE) is a malformed JSON.
Stream:
Removed set_socket_blocking(), equivalent to its alias stream_set_blocking().
XSL:
Remove xsl.security_prefs ini option and use XsltProcessor::setSecurityPrefs() instead.
2. New features
Core
Added group use statement. (RFC: https://wiki.php.net/rfc/group_use_declarations)
Added null coalescing operator (??). (RFC: https://wiki.php.net/rfc/isset_ternary)
Supports strings >= 231 bytes in length on 64-bit architectures.
Added Closure::call() method (only works on user-side classes).
Added u{xxxxxx} Unicode codepoint escape format to double quoted strings and here documentation.
define() now supports arrays as constant values, fixing an oversight when define() did not yet support array constant values.
Added comparison operator (96b4fef55684b9312718d5de63fb7121), the spaceship operator. (RFC: https://wiki.php.net/rfc/combined-comparison-operator)
Added coroutine-like yield from operator for delegate generators. (RFC: https://wiki.php.net/rfc/generator-delegation)
Reserved keywords can now be used in several new contexts. (RFC: https://wiki.php.net/rfc/context_sensitive_lexer)
Added declaration support for scalar types, and can use declare(strict_types=1) in declare strict mode. (RFC:https://wiki.php.net/rfc/scalar_type_hints_v5)
Added support for cryptographically secure user-side random number generators. (RFC: https://wiki.php.net/rfc/easy_userland_csprng)
Opcache
Added file-based second-level opcode caching (experimental - disabled by default). To enable it, PHP needs to be configured and built with --enable-opcache-file, and then the opcache.file_cache=22a3afa6929a2c87025fe3045a234971 configuration directive can be set in php.ini. Second level cache may improve performance on server restarts or SHM resets. Alternatively, you can set opcache.file_cache_only=1 to use file caching without SHM at all (perhaps useful for shared hosting); set opcache.file_cache_consistency_checks=0 to disable file cache consistency checks to speed up the loading process, which is a security risk.
OpenSSL
When building with OpenSSL 1.0.2 and newer, the "alpn_protocols" SSL context option has been added to allow encrypted client/server streams to use the ALPN TLS extension to negotiate alternative protocols. Negotiated protocol information can be accessed via the stream_get_meta_data() output.
Reflection
Added a ReflectionGenerator class (yield from Traces, current file/line, etc.).
A ReflectionType class has been added to better support new return types and scalar type declaration capabilities. The new ReflectionParameter::getType() and ReflectionFunctionAbstract::getReturnType() methods both return a ReflectionType instance.
Stream
Added new Windows-only stream context option to allow blocking pipe reads. To enable this feature, pass array("pipe" => array("blocking" => true)) when creating the stream context. Be aware that this option can cause pipe buffer deadlocks, however it is useful in several command line scenarios.
3. Changes in SAPI module
FPM
Fixed bug #65933 (Cannot set configuration lines exceeding 1024 bytes).
Listen = port now listens on all addresses (IPv6 and IPv4 mapped).
4. Deprecated features
Core
Deprecated PHP 4 style constructors (i.e. the constructor name must be the same as the class name).
Static calls to non-static methods are deprecated.
OpenSSL
Deprecated "capture_session_meta" SSL context option. Encryption-related metadata active on the stream resource can be accessed through the return value of stream_get_meta_data().
5. Changes in functions
parse_ini_file():
parse_ini_string():
Added scan mode INISCANNERTYPED to get .ini values of yield type.
unserialize():
Added a second parameter to the unserialize function (RFC: https://wiki.php.net/rfc/secure_unserialize) to specify acceptable classes: unserialize($foo, ["allowed_classes" => [" MyClass", "MyClass2"]]);
proc_open():
The maximum number of pipes that could be used by proc_open() was previously hard-coded limited to 16. This limitation is now removed and is only limited by the available memory size of PHP.
The newly added Windows-only configuration option "blocking_pipes" can be used to force blocking reading from child process pipes. This can be used in several command line scenarios, but it can lead to deadlocks. Additionally, this is related to the new stream's pipeline context options.
array_column():
This function now supports treating object arrays as two-dimensional arrays. Only public properties will be processed, and dynamic properties using __get() in the object must also implement __isset().
stream_context_create()
Now accepts a Windows-only configuration array("pipe" => array("blocking" => 78180fd7e2f5f09e138c95a71ada14e6)) to force blocking pipe reads. This option should be used with caution, as this platform may cause deadlocks in the pipe buffer.
6. New function
GMP
Added gmp_random_seed().
PCRE:
Added preg_replace_callback_array function. (RFC: https://wiki.php.net/rfc/preg_replace_callback_array)
Standard . Added intdiv() function for integer division. . Added error_clear_last() function that resets error status.
Zlib: . Added deflate_init(), deflate_add(), inflate_init(), inflate_add() functions to run incremental and streaming compression/decompression.
7. New classes and interfaces
(None yet)
8. Removed extensions and SAPI
sapi/aolserver
sapi/apache
sapi/apache_hooks
sapi/apache2filter
sapi/caudium
sapi/continuity
sapi/isapi
sapi/milter
sapi/nsapi
sapi/phttpd
sapi/pi3web
sapi/roxen
sapi/thttpd
sapi/tux
sapi/webjames
ext/mssql
ext/mysql
ext/sybase_ct
ext/ereg
For more details, see:
https://wiki.php.net/rfc/removal_of_dead_sapis_and_exts
https://wiki.php.net/rfc/remove_deprecated_functionality_in_php7
Note: NSAPI is not voted on in the RFC, but it will be removed at a later date. This means that its associated SDK will not be available going forward.
9. Other changes to the extension
Mhash
Mhash is no longer an extension, use function_exists("mhash") to check if the tool is available.
10. New global constants
Core . Add PHP_INT_MIN
Zlib
These constants were added to control the refresh behavior of the new inflate deflate_add() and inflate_add() functions:
ZLIB_NO_FLUSH
ZLIB_PARTIAL_FLUSH
ZLIB_SYNC_FLUSH
ZLIB_FULL_FLUSH
ZLIB_BLOCK
ZLIB_FINISH
GD
Removed T1Lib support so that due to optional dependency on T1Lib, the following will not be available in the future:
Function:
imagepsbbox()
imagepsencodefont()
imagepsextendedfont()
imagepsfreefont()
imagepsloadfont()
imagepsslantfont()
imagepstext()
Source:
'gd PS font'
'gd PS encoding'
11. Changes in INI file handling
Core
Removed asp_tags ini directive. Enabling it will cause a fatal error.
Removed always_populate_raw_post_data ini directive.
12. Windows support
Core
Support native 64-bit integers on 64-bit systems.
Support for large files on 64-bit systems.
Support getrusage().
ftp
The ftp extension provided is always a shared library.
For SSL support, the dependency on the openssl extension has been removed and only the openssl library is relied upon instead. ftp_ssl_connect() is automatically enabled if required at compile time.
odbc
The odbc extension provided is always a shared library.
13. Other changes
Core
NaN and Infinity are always 0 when converted to integers and are not undefined and platform-dependent.
Calling a method on a non-object triggers a catchable error rather than a fatal error; see: https://wiki.php.net/rfc/catchable-call-to-member-of-non-object
zend_parse_parameters, type hints, and conversions now always use "integer" and "float" instead of "long" and "double".
If ignore_user_abort is set to true, output caching will continue to work for interrupted connections.