The new version of PHP7.0 not only greatly improves performance but also changes a lot in terms of language features, see below for specific explanations:
1. Backward incompatible changes
Language change
Change in variable handling
Indirect variables, properties, and method references are now interpreted from left to right semantics. Some examples:
$ $foo [' bar '] [' baz ']//Interpretation ($ $foo) [' Bar '] [' Baz ']
$foo-> $bar [' baz ']//interpreted ($foo-> $bar) [' Baz ']
$foo- > $bar [' Baz '] ()//interpreted to do ($foo-> $bar) [' Baz '] ():
: $bar [' Baz '] ()//Interpret Do (foo:: $bar) [' Baz '] ()
To restore previous behavior, you need to explicitly increase the parentheses:
${$foo [' Bar '] [' Baz ']}
$foo->{$bar [' Baz ']}
$foo->{$bar [' Baz ']} ()
foo::{$bar [' Baz ']} ()
Global keywords now accept only simple variables. Like the old
Copy Code code as follows:
Now ask for the following wording:
Copy Code code as follows:
The parentheses around the variable or function call no longer have any effect. For example, the following code, a function call result, is passed to a function by reference
function GetArray () {return [1, 2, 3];}
$last = Array_pop (GetArray ());
STRICT standards: Only variables can be passed by reference
$last = Array_pop ((GetArray ()));
STRICT standards: Only variables can be passed in a reference way
Now, whether or not parentheses are used, a strict standard error will be thrown. Previously, there was no hint in the second invocation mode.
An array element or object property automatically installs the reference order, and the result order is now different. For example:
$array = [];
$array ["A"] =& $array ["B"];
$array ["b"] = 1;
Var_dump ($array);
Now the result is ["a" => 1, "B" => 1], and the previous result is ["B" => 1, "a" => 1]
Related RFCs:
Https://wiki.php.net/rfc/uniform_variable_syntax
Https://wiki.php.net/rfc/abstract_syntax_tree
The change of list ()
List () is no longer assigned in reverse order, for example:
Copy Code code 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 assignment order is changed, and the assignment is still consistent (LCTT: the previous list () behavior is assigned one at a time from a later variable, which results in [3,2,1] for this usage. )。 For example, a general usage similar to the following
Copy Code code as follows:
List ($a, $b, $c) = [1, 2, 3];
$a = 1; $b = 2; $c = 3;
Still keep the current behavior.
The empty list () is no longer allowed to be assigned a value. If the following are all invalid:
List () = $a;
List (,,) = $a;
List ($x, List (), $y) = $a;
List () no longer supports splitting of strings (previously supported only in some cases)
The following code:
Copy Code code as follows:
$string = "XY";
List ($x, $y) = $string;
Now the result is: $x = = null and $y = NULL (no hint), and the previous result is: $x = = "X" and $y = = "Y".
In addition, the list () is now always able to handle objects that implement arrayaccess, such as:
Copy Code code as follows:
List ($a, $b) = (object) new Arrayobject ([0, 1]);
Now the result is: $a = = 0 and $b = 1. Previously $a and $b were null.
Related RFCs:
Https://wiki.php.net/rfc/abstract_syntax_tree#changes_to_list
Https://wiki.php.net/rfc/fix_list_behavior_inconsistency
The change of foreach
The foreach () iteration no longer affects an array internal pointer, which can be accessed through a series of functions such as current ()/next (). For example:
Copy Code code as follows:
$array = [0, 1, 2];
foreach ($array as & $val) {
Var_dump (current ($array));
}
Now point to the value int (0) three times. The previous output was int (1), int (2), and bool (false).
When an array is iterated by value, foreach always operates on an array copy, and any array operations in the iteration do not affect the iteration behavior. For example:
Copy Code code 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, and the second element 1 will be skipped (0 2) before.
When an array is iterated by reference, modifications to the array continue to affect the iteration. However, now PHP can better maintain the position within the array when using numbers as keys. For example, add an array element to the iteration by reference:
Copy Code code as follows:
$array = [0];
foreach ($array as & $val) {
Var_dump ($val);
$array [1] = 1;
}
Now the iteration will correctly add the element. The above code output is "int (0) int (1)", which previously was just "int (0)".
The behavior of a normal (not-traversed) object by value or by reference is similar to iterating over an array by reference. This conforms to previous behavior, in addition to the more precise position management improvements described in the previous point.
The iterative behavior of the Ergodic object remains unchanged.
Related Rfc:https://wiki.php.net/rfc/php7_foreach
Changes in Parameter handling
You cannot define two function parameters with the same name. For example, the following method triggers a compile-time error:
Copy Code code as follows:
Public function foo ($a, $b, $unused, $unused) {
// ...
}
The code above should be modified using a different parameter name, such as:
Copy Code code as follows:
Public function foo ($a, $b, $unused 1, $unused 2) {
// ...
}
Instead of returning the original value passed to the parameter, the Func_get_arg () and Func_get_args () functions return their current value (which may be modified). For example:
Copy Code code as follows:
function foo ($x) {
$x + +;
Var_dump (Func_get_arg (0));
}
Foo (1);
Will print "2" instead of "1". The code should be changed to modify the operation only after calling Func_get_arg (s).
Copy Code code as follows:
function foo ($x) {
Var_dump (Func_get_arg (0));
$x + +;
}
Or you should avoid modifying parameters:
Copy Code code as follows:
function foo ($x) {
$newX = $x + 1;
Var_dump (Func_get_arg (0));
}
Similarly, exception backtracking does not show the original value passed to the function, but the modified value. For example:
Copy Code code as follows:
function foo ($x) {
$x = 42;
throw new Exception;
}
Foo ("string");
Now the result of the stack trace is:
Copy Code code as follows:
Stack Trace:
#0 file.php (4): foo (42)
#1 {main}
And it used to be:
Copy Code code as follows:
Stack Trace:
#0 file.php (4): foo (' string ')
#1 {main}
This does not affect the run-time behavior of your code, and it is worth noting that it will be different when debugging.
The same restrictions also affect debug_backtrace () and other functions that check function arguments.
Related Rfc:https://wiki.php.net/phpng
Changes in integer processing
An invalid octal representation (containing a number greater than 7) now produces a compilation error. For example, the following code is no longer valid:
$i = 0781; 8 is not a valid octal number!
Previously, invalid numbers (and any numbers after an invalid number) were simply ignored. The previous $i value is 7 because the latter two digits are silently discarded.
Binary with a negative mirror displacement now throws an arithmetic error:
Copy Code code as follows:
Arithmeticerror: Displacement with negative numbers
When the number of digits left shifted exceeds the integer width, the result is always 0.
Copy Code code as follows:
Var_dump (1 << 64); Int (0)
The results of previous code above depend on the CPU architecture used. For example, on x86 (including x86-64) The result is int (1) because the displacement operand is in range.
Similarly, when the number of digits to the right shift exceeds the integer width, the result is always 0 or-1 (dependent on the symbol):
Copy Code code as follows:
Var_dump (1 >> 64); Int (0)
Var_dump ( -1 >> 64); Int (-1)
Related Rfc:https://wiki.php.net/rfc/integer_semantics
Change in string handling
Strings containing 16-digit numbers are no longer used as numbers and are not handled specially. See the new behavior in the example:
Copy Code code as follows:
Var_dump ("0x123" = = "291"); BOOL (FALSE) (formerly True)
Var_dump (Is_numeric ("0x123")); BOOL (FALSE) (formerly True)
Var_dump ("0xe" + "0x1"); Int (0) (formerly 16)
Var_dump (substr ("foo", "0x1")); String (3) "Foo" (formerly "oo")
Note: You have encountered a number that is not in the normal format
Filter_var () can be used to check whether a string contains a hexadecimal number, or whether the string can be converted to an integer:
$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)
Because the Unicode code point escape Format (Unicode codepoint escape Syntax) is added to the double quote string and the here document, "\u{" with an invalid sequence now causes an error:
$str = "\u{xyz}"; Fatal error: Invalid UTF-8 code point escape sequence
To avoid this situation, you need to escape the opening backslash:
$str = "\\u{xyz}"; That's right
However, the "\u" that does not follow {is not affected. The following code does not generate an error and works as before:
$str = "\u202e"; That's right
Related RFCs:
Https://wiki.php.net/rfc/remove_hex_support_in_numeric_strings
Https://wiki.php.net/rfc/unicode_escape
Change in error handling
There are now two exception classes: Exception and Error. All two classes implement a new interface: Throwable. The type indication in the exception handling code may need to be modified to handle this situation.
Some fatal errors and recoverable fatal errors are now thrown to an error. Because the Error is a separate Exception class, these exceptions are not captured by an existing Try/catch block.
Recoverable fatal errors are converted to an exception, so they cannot be silently ignored in error handling. In some cases, the type indicates that the failure can no longer be ignored.
Parsing errors now generate an error-extended parseerror. In addition to previous processing based on the return value/Errorgetlast (), the error handling for eval () of some potentially invalid code should be changed to capture ParseError.
The constructor of an inner class always throws an exception when it fails. Some previous constructors return NULL or an object that is not available.
Some e_strict prompts have changed the error level.
Related RFCs:
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
Other changes in language
Static invocation of an incompatible $this context is no longer supported by a non-static invocation. In this case, the $this is undefined, but the call to it is allowed and comes with an obsolete hint. Example:
Class A {public
function test () {var_dump ($this);}
}
Note: There is no extended
class B {public
function Callnonstaticmethodofa () {a::test ()}
}
from class A (New B)->callnonstaticmethodofa ();
Discard: Non-static method A::test () should not be called statically
Hint: undefined variable $this
Null
Note that this only occurs on calls from an incompatible context. If class B extends from class A, the call is allowed without any hint.
You cannot use the following class names, interface names, and special names (case sensitive):
bool
Int
Float
String
Null
False
True
This is used in class/interface/trait declarations, Class_alias (), and use statements.
In addition, the following class names, interface names, and special names are reserved for future use, but the use of fashion does not throw errors:
Resource
Object
Mixed
Numeric
Yield statement structure when used in an expression context, parentheses are no longer required. It is now a right associative operator between "print" and "=>". In some cases this can lead to different behaviors, such as:
Echo yield-1;
Was previously interpreted as follows
Echo (yield)-1;
is now interpreted as follows
Echo Yield (-1);
Yield $foo or die;
Was previously interpreted as follows
Yield ($foo or die);
is now interpreted as follows
(yield $foo) or die;
This situation can be solved by adding parentheses.
Remove ASP (<%) and script (<script language=php>) label.
Rfc:https://wiki.php.net/rfc/remove_alternative_php_tags
It is not supported to assign values to new results in a reference way.
Calls are not supported on a domain from a non-static method that is not a compatible $this context. Details see also: Https://wiki.php.net/rfc/incompat_ctx.
The # Style notes in the INI file are not supported. Use Style of note substitution.
$HTTP _raw_post_data is no longer available and uses php://input stream substitution.
Changes to the standard library
Call_user_method () and Call_user_method_array () no longer exist.
When an output buffer is created in the output buffer processor, Ob_start () no longer emits e_error, but e_recoverable_error.
Improved Zend_qsort (using the hybrid sorting algorithm) performs better and is renamed Zend_sort.
Increase the static sort algorithm zend_insert_sort.
Remove the fpm-fcgi DL () function.
Setcookie () If the cookie name is empty, it triggers a WARNING instead of emitting an empty Set-cookie header.
Other
Curl:
Remove support for disabling the curlopt_safe_upload option. All curl file uploads must use the Curl_file/curlfile API.
Date:
Remove $is _dst parameters from Mktime () and Gmmktime ()
Dba
If the key does not appear in the Inifile processor, Dba_delete () will now return false.
Gmp
LIBGMP version 4.2 or update is now required.
Gmp_setbit () and Gmp_clrbit () return FALSE for negative metrics, consistent with other GMP functions.
INTL:
Remove discarded aliases datefmt_set_timezone_id () and Intldateformatter::settimezoneid (). Instead of using Datefmt_set_timezone () and Intldateformatter::settimezone ().
Libxml
Add libxml_biglines parser Options. is available from Libxml 2.9.0 and adds support for the line number greater than 16 digits in the error report.
Mcrypt
Removes the discarded alias Mcrypt_generic_end () that is equivalent to Mcrypt_generic_deinit ().
Removes discarded MCRYPT_ECB (), MCRYPT_CBC (), MCRYPT_CFB (), and MCRYPT_OFB () functions, which are equivalent to mcrypt_mode_* () and mcrypt_encrypt using the MCRYPT_DECR flag Ypt ().
Session
Session_Start () accepts all INI settings as an array. For example, [' Cache_limiter ' => ' private '] sets session.cache_limiter=private. also supports ' Read_and_close ' to close session data immediately after reading the data.
The session-save processor accepts the use of Validate_sid () and Update_timestamp () to verify that the session ID exists and updates the session timestamp. continues to be compatible with legacy user-defined session-save processors.
increased the sessionupdatetimestamphandlerinterface. Validatesid (), Updatetimestamp () are defined in the interface.
Session.lazy_write (default is on) INI setting supports writing only when session data is updated.
Opcache
Removes the Opcache.load_comments configuration statement. The comments in the file are now loaded without cost and are always enabled.
Openssl:
Removes the "rsa_key_size" SSL context option and automatically sets the appropriate size according to the negotiated encryption algorithm given.
Removes the "Cn_match" and "Sni_server_name" SSL contextual selections. Use automatic detection or the "peer_name" option instead.
PCRE:
Removes support for the/e (preg_replace_eval) modifier using preg_replace_callback () substitution.
Pdo_pgsql:
Remove the Pgsql_attr_disable_native_prepared_statement attribute, equivalent to Attr_emulate_prepares.
Standard:
Removes the string class support in setlocale (). Replace with Lc_* constants. instead.
Remove Set_magic_quotes_runtime () and its alias Magic_quotes_runtime ().
Json:
The RFC 7159 incompatible number format in Json_decode is rejected-top level (0xFF,. 1,-.1) and all layers ([1.], [1.e1])
Calling Json_decode with one argument is equivalent to an empty PHP string or value invocation, and the result of converting to an empty string (null, FALSE) is a JSON format error.
Stream:
removing set_socket_blocking () is equivalent to its alias stream_set_blocking ().
Xsl:
Remove the xsl.security_prefs ini option and use Xsltprocessor::setsecurityprefs () instead.
2. New Features
Core
The
Adds a group use declaration. (rfc:https://wiki.php.net/rfc/group_use_declarations) The
adds a null merge operator (??). (rfc:https://wiki.php.net/rfc/isset_ternary) The
supports a string of length >= 231 bytes on a 64-bit schema. The
adds the Closure::call () method (the class that works only on the user side). The
adds the \u{xxxxxx} Unicode code point escape format in double quote strings and here documents. The
define () now supports arrays as constant values, fixing an oversight when define () does not support array constant values. The
adds the comparison operator (<=>), which is the spacecraft operator. (Rfc:https://wiki.php.net/rfc/combined-comparison-operator) The
adds a yield from operator that resembles a coprocessor for the delegate builder. (rfc:https://wiki.php.net/rfc/generator-delegation) The
reserved keywords can now be used in several new contexts. (rfc:https://wiki.php.net/rfc/context_sensitive_lexer) The
adds a scalar type of declarative support and can use the declare (strict_types=1) Declaration strict mode. (RFC:HTTPS://WIKI.PHP.NET/RFC/SCALAR_TYPE_HINTS_V5) The
adds support for the random number generator on the secure user side of the encryption level. (RFC:HTTPS://WIKI.PHP.NET/RFC/EASY_USERLAND_CSPRNG)
Opcache
Increased file-based Two-level opcode caching (experimental--default disabled). To enable it, PHP needs to use--enable-opcache-file configuration and build, and then opcache.file_cache=<dir> configuration instructions can be set in php.ini. A secondary cache may increase the performance of a server reboot or SHM reset. Alternatively, you can set up Opcache.file_cache_only=1 to use the file cache without SHM (perhaps useful for shared hosts); set opcache.file_cache_consistency_checks=0 To disable file cache consistency checking to speed up the loading process with a security risk.
Openssl
When built with OpenSSL 1.0.2 and updates, the "Alpn_protocols" SSL contextual entries are added to allow encrypted client/server streams to negotiate alternative protocols using the ALPN TLS extension. The negotiated protocol information can be accessed through Stream_get_meta_data () output.
Reflection
Added a Reflectiongenerator class (yield from traces, current file/line, etc.).
Added a Reflectiontype class to better support the new return type and scalar type declaration capabilities. Both the new Reflectionparameter::gettype () and Reflectionfunctionabstract::getreturntype () methods return a Reflectiontype instance.
Stream
Added a new streaming context option for Windows only to allow blocking pipe reads. To enable this feature, pass array ("pipe" => Array ("blocking" => true) when the stream context is created. Note that this option causes a deadlock in the pipeline buffer, but it is useful in several command-line scenarios.
3. Changes in SAPI modules
Fpm
Fix error #65933 (Cannot set more than 1024 bytes of configuration row).
Listen = port is now listening on all addresses (IPV6 and IPv4 mappings).
4. Obsolete functions
Core
Deprecated the PHP 4-style build function (that is, the constructor name must be the same as the class name).
A static call to a Non-static method is discarded.
Openssl
The "Capture_session_meta" SSL contextual selections were discarded. Encryption-related metadata that is active on a stream resource can be accessed through the return value of Stream_get_meta_data ().
5. Changes in functions
Parse_ini_file ():
Parse_ini_string ():
A scan mode iniscannertyped was added to get the. ini value of the yield type.
Unserialize ():
Add a second argument (rfc:https://wiki.php.net/rfc/secure_unserialize) to the Unserialize function to specify the acceptable class: Unserialize ($foo, ["Allowed_ Classes "=> [" MyClass "," MyClass2 "]]);
Proc_open ():
The maximum number of pipes that can be used by Proc_open () is previously limited to 16 hard-coded. Now to go beyond this limit, only limited to the amount of memory available in PHP.
The newly added configuration option "Blocking_pipes", which is used only for Windows, can be used to force a blocking of read from the Subprocess pipeline. This can be used for several command-line scenarios, but it causes deadlocks. In addition, this is related to the new stream's pipeline context selections.
Array_column ():
The function now supports the array of objects as a two-dimensional array. Only public properties are processed, and dynamic properties that use __get () within an object must also implement __isset ().
Stream_context_create ()
You can now accept a Windows-only available configuration array ("Pipe" => Array ("Blocking" => <boolean>) to force blocking of pipe reads. This option should be used with care, and the platform may cause a deadlock in the pipeline buffer.
6. New function
Gmp
Added Gmp_random_seed ().
PCRE:
Added the Preg_replace_callback_array function. (Rfc:https://wiki.php.net/rfc/preg_replace_callback_array)
Standard. Added integer division Intdiv () function ... Added the Error_clear_last () function to reset the error state.
Zlib:. Added Deflate_init (), Deflate_add (), Inflate_init (), Inflate_add () functions to run increment and stream compression/decompression.
7. New classes and interfaces
(NO)
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
More details see also:
Https://wiki.php.net/rfc/removal_of_dead_sapis_and_exts
Https://wiki.php.net/rfc/remove_deprecated_functionality_in_php7
Note: NSAPI does not vote in the RFC, but it will be removed later. This means that the SDK associated with it is not available in the future.
9. Other changes in the expansion
Mhash
Mhash is not an extension in the future, using Function_exists ("Mhash") to check whether the device is available.
10. New Global Constants
Core. Add Php_int_min
Zlib
These constants are added to control the refresh behavior of the new incremental Deflate_add () and Inflate_add () functions:
Zlib_no_flush
Zlib_partial_flush
Zlib_sync_flush
Zlib_full_flush
Zlib_block
Zlib_finish
Gd
Remove T1lib support, which is not available in the future due to an optional dependency on T1lib:
Function:
Imagepsbbox ()
Imagepsencodefont ()
Imagepsextendedfont ()
Imagepsfreefont ()
Imagepsloadfont ()
Imagepsslantfont ()
Imagepstext ()
Resources:
' GD PS font '
' GD PS encoding '
Changes in the processing of one. INI file
Core
Remove the asp_tags INI directive. If enabled, it can cause fatal errors.
Remove the always_populate_raw_post_data INI directive.
Windows Support
Core
Native 64-bit integers are supported on 64-bit systems.
Large files are supported on 64-bit systems.
Support for Getrusage ().
Ftp
The FTP extension you bring is always shared with the library.
For SSL support, the dependency on the OpenSSL extension is eliminated, and the OpenSSL library is relied on instead. If required at compile time, Ftp_ssl_connect () is automatically enabled.
Odbc
The ODBC extension you bring is always shared with the library.
13. Other changes
Core
NaN and Infinity are always 0 when converted to integers, not undefined and platform-dependent.
Calling a method on a non-object triggers a catch error, not a fatal error; see also: Https://wiki.php.net/rfc/catchable-call-to-member-of-non-object
Zend_parse_parameters, type hints, and transformations, now always use "integer" and "float" instead of "long" and "double".
If the Ignore_user_abort is set to True, the output cache continues to work with the disconnected connection.