Performance improvements: PHP 7 up to twice times faster PHP 5.6
Significantly reduced memory usage
Abstract syntax Tree
Consistent 64-bit support
Improved exception hierarchies
Many conversions to fatal errors
Safe Random number generator
Remove old and unsupported Sapis and extensions
Empty merge operator (? )
Return and scalar type declarations
Anonymous class
0 Cost Assertion
1. Test Case One:
Generates 500,000 arrays and queries 500,000 times if a key exists
<?php
$a = array ();
for ($i =0; $i <500000; $i + +) {
$a [$i] = $i;
}
foreach ($a as $i)
{
Array_key_exists ($i, $a);
}
?>
The test results are as follows:
? Time PHP test.php
PHP test.php
0.60s User
0.05s system
98% CPU
0.667 Total
? time/usr/local/php7/bin/php test.php
/usr/local/php7/bin/php test.php
0.05s User
0.02s system
92% CPU
0.073 Total
PHP7 is 9 times times faster than PHP5.5.
2. Test Case TWO:
Generates 500,000 arrays and queries 500,000 times if value exists
<?php
$a = array ();
for ($i =0; $i <10000; $i + +) {
$a [$i] = $i;
}
foreach ($a as $i)
{
Array_key_exists ($i, $a);
}
?>
? Time PHP test.php
PHP test.php
0.79s User
0.01s system
99% CPU
0.809 Total
? time/usr/local/php7/bin/php test.php
/usr/local/php7/bin/php test.php
0.08s User
0.01s system
97% CPU
0.091 Total
PHP7 is 8.7 times times faster than PHP5.5.
3. Test Case THREE:
Examples and results from the Bird Brother blog. Based on Wordpress, Test PHP7 and HHVM3.2. Use the Apache AB Test tool. 100 concurrent, 10,000 requests. Pre-test will be warmed up with 100 requests.
PHP7 results are as follows:
Concurrency level:100
Time taken for tests:38.726 seconds
Complete requests:10000
Failed requests:0
Write errors:0
Total transferred:89290000 bytes
HTML transferred:86900000 bytes
Requests per second:258.22 [#/sec] (mean)
Time per request:387.260 [MS] (mean)
Time per request:3.873 [MS] (mean, across all concurrent requests)
Transfer rate:2251.64 [Kbytes/sec] Received
HHVM-3.2
HHVM results are as follows:
Document Path:/wordpress/
Document length:8690 bytes
Concurrency level:100
Time taken for tests:43.296 seconds
Complete requests:10000
Failed requests:0
Write errors:0
Total transferred:89260000 bytes
HTML transferred:86900000 bytes
Requests per second:230.97 [#/sec] (mean)
Time per request:432.957 [MS] (mean)
Time per request:4.330 [MS] (mean, across all concurrent requests)
Transfer rate:2013.31 [Kbytes/sec] Received
php7–258.22 QPS hhvm–230.97 QPS
Iv. new features 1, scalar type declaration
There are two modes: mandatory (default) and strict mode. You can now use the following type parameters, whether in forced or strict mode: string (String), Integer (int), floating-point number (float), and Boolean (bool). They augment the other types introduced in PHP5: Class name, interface, array, and callback type. In the old version, the function parameter declaration can only be (Array $arr), (CLassName $obj), etc., basic types such as Int, string, etc. are not able to be declared
<?php
function check (int $bool) {
Var_dump ($bool);
}
Check (1);
Check (TRUE);
?>
If no coercion type is cast, an int (1) bool (TRUE) is entered. output bool (TRUE) bool (true) after conversion
2. return value type declaration
PHP 7 adds support for return type declarations. The return type declaration indicates the type of the function return value. The available types are the same as the types 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], [4,5,6], [7,8,9]);
The above routines will output:
Array
(
[0] = 6
[1] = 15
[2] = 24
)
3, NULL merge operator
There is a large number of simultaneous use of ternary expressions and isset () in the project, adding the null merge operator (??). This grammatical sugar. If a variable exists and the value is not NULL, it returns its own value, otherwise it returns its second operand.
Old version: Isset ($_get[' id ')? $_get[id]: Err;
NEW: $_get[' id '?? ' Err ';
4. Spaceship operator (combination comparator)
The spaceship operator is used to compare two expressions. When $a is greater than, equal to, or less than $b, it returns-1, 0, or 1, respectively. The principle of comparison is to follow the regular comparison rules of PHP.
<?php
Integers
echo 1 <=> 1; 0
echo 1 <=> 2; -1
echo 2 <=> 1; 1
Floats
Echo 1.5 <=> 1.5; 0
echo 1.5 <=> 2.5; -1
echo 2.5 <=> 1.5; 1
Strings
echo "A" <=> "a"; 0
echo "A" <=> "B"; -1
echo "B" <=> "a"; 1
?>
5. Define a constant array by define ()
<?php
Define (' ANIMALS ', [' dog ', ' cat ', ' bird ');
Echo Animals[1]; Outputs "Cat"
?>
6. Anonymous class
It is now supported to instantiate an anonymous class with the new class, which can be used instead of some full-burn class definitions.
<?php
Interface Logger {
Public function log (string $msg);
}
Class Application {
Private $logger;
Public Function GetLogger (): Logger {
return $this->logger;
}
Public Function Setlogger (Logger $logger) {
$this->logger = $logger;
}
}
$app = new Application;
$app->setlogger (new class implements Logger {
Public function log (string $msg) {
Echo $msg;
}
});
Var_dump ($app->getlogger ());
7. Unicode codepoint Translation Syntax
This accepts a Unicode codepoint in the form of 16, and prints a string in a double-quote or heredoc-enclosed UTF-8 encoded format. Any valid codepoint can be accepted, and 0 of the beginning can be omitted.
<?php
echo "\u{9876}"
?>
Legacy output: \u{9876}
New input: Top
8, Closure::call ()
Closure::call () now has better performance, a short, skilful way to temporarily bind a method to a closure on an object and invoke it.
<?php
Class Test{public $name = "Lixuan";}
Both PHP7 and PHP5.6 can
$getNameFunc = function () {return $this->name;};
$name = $getNameFunc->bindto (new test, ' test ');
echo $name ();
PHP7 can, PHP5.6 error
$getX = function () {return $this->name;};
Echo $getX->call (new Test);
9. Provide filtering for unserialize ()
This feature is designed to provide a more secure way of unpacking unreliable data. It prevents potential code injection by using a whitelist approach.
<?php
Divides all objects into __php_incomplete_class objects
$data = Unserialize ($foo, ["allowed_classes" = false]);
Divides all objects into __php_incomplete_class objects in addition to CLASSNAME1 and ClassName2
$data = Unserialize ($foo, ["allowed_classes" + = ["ClassName1", "ClassName2"]);
Default behavior, same as Unserialize ($foo)
$data = Unserialize ($foo, ["allowed_classes" = true]);
10, Intlchar
The newly added Intlchar class is designed to expose more ICU functionality. This class itself defines a number of static methods used to manipulate Unicode characters for multiple character sets. Intl is a Pecl extension that needs to be compiled into PHP before use, or Apt-get/yum/port install Php5-intl
<?php
printf ('%x ', Intlchar::codepoint_max);
echo intlchar::charname (' @ ');
Var_dump (intlchar::ispunct ('! '));
?>
The above routines will output:
10ffff
Commercial at
BOOL (TRUE)
11. Expected
It is expected that the previous assert () method is used backwards and strengthened. It enables the assertion to be zero-cost in a production environment, and provides the ability to throw specific exceptions when an assertion fails. The old version of the API will continue to be maintained for compatibility purposes, and assert () is now a language structure that allows the first argument to be an expression, not just a string to be computed or a Boolean to be tested.
<?php
Ini_set (' assert.exception ', 1);
Class Customerror extends Assertionerror {}
ASSERT (False, new Customerror (' Some error message '));
?>
The above routines will output:
Fatal error:uncaught customerror:some Error message
12. Group Use declarations
Classes, functions, and constants imported from the same namespace can now be imported once with a single use statement.
<?php
Before PHP7
Use Some\namespace\classa;
Use SOME\NAMESPACE\CLASSB;
Use SOME\NAMESPACE\CLASSC as C;
Use function some\namespace\fn_a;
Use function Some\namespace\fn_b;
Use function Some\namespace\fn_c;
Use const Some\namespace\consta;
Use const SOME\NAMESPACE\CONSTB;
Use const SOME\NAMESPACE\CONSTC;
After PHP7
Use Some\namespace\{classa, ClassB, ClassC as C};
Use function some\namespace\{fn_a, Fn_b, Fn_c};
Use const Some\namespace\{consta, CONSTB, CONSTC};
?>
13, Intdiv ()
Receives two parameters as dividend and divisor, returning the integer portion of the result of their division.
<?php
Var_dump (Intdiv (7, 2));
?>
Output int (3)
14, Csprng
Two new functions are added: Random_bytes () and Random_int (). You can encrypt the production of protected integers and strings. My crappy translation, in short, the random number becomes safe.
andom_bytes-encryption survival protected pseudo-random string
random_int-encryption survival protected pseudo-random integer
15, Preg_replace_callback_array ()
A new function, Preg_replace_callback_array (), is used to make the code more elegant when using the Preg_replace_callback () function. Before PHP7, the callback function invokes each regular expression, and the callback function is contaminated on some branches.
16. Session Options
Now, the session_start () function can receive an array as an argument, overwriting the configuration of the session in PHP.ini.
For example, set the Cache_limiter to private and close immediately after reading the session.
<?php
Session_Start ([
' Cache_limiter ' = ' private ',
' Read_and_close ' = true,
]);
?>
17, the Generator return value
The concept of introducing generators in PHP5.5. The generator function gets a yield ID value each time it executes. In PHP7, when the generator iteration is complete, you can get the return value of the generator function. obtained by Generator::getreturn ().
<?php
function Generator () {
Yield 1;
Yield 2;
Yield 3;
Return "a";
}
$generatorClass = ("generator") ();
foreach ($generatorClass as $val) {
echo $val. " “;
}
echo $generatorClass->getreturn ();
?>
Output is: 1 2 3 A
18. Introducing other generators into the generator
You can introduce another or several generators in the generator, just write yield from functionName1
<?php
function Generator1 () {
Yield 1;
Yield 2;
Yield from Generator2 ();
Yield from Generator3 ();
}
function Generator2 () {
Yield 3;
Yield 4;
}
function Generator3 () {
Yield 5;
Yield 6;
}
foreach (Generator1 () as $val) {
echo $val, "";
}
?>
Output: 1 2 3 4 5 6
V. Incompatibility 1, foreach no longer changes the internal array pointer
Before PHP7, when an array passes through a foreach iteration, the array pointer moves. Starting now, no longer, see the code below.
<?php
$array = [0, 1, 2];
foreach ($array as & $val) {
Var_dump (current ($array));
}
?>
PHP5 output:
Int (1)
Int (2)
BOOL (FALSE)
PHP7 output:
Int (0)
Int (0)
Int (0)
2. Foreach has better iterative characteristics when traversing by reference
When iterating through arrays using references, foreach now has better track changes in iterations. For example, to add an iteration value to an array in an iteration, refer to the following code:
<?php
$array = [0];
foreach ($array as & $val) {
Var_dump ($val);
$array [1] = 1;
}
?>
PHP5 output:
Int (0)
PHP7 output:
Int (0)
Int (1)
3. The hexadecimal string is no longer considered a number
A hexadecimal string is no longer considered a number
<?php
Var_dump ("0x123" = = "291");
Var_dump (Is_numeric ("0x123"));
Var_dump ("0xe" + "0x1");
Var_dump (substr ("foo", "0x1"));
?>
PHP5 output:
BOOL (TRUE)
BOOL (TRUE)
Int (15)
String (2) "oo"
PHP7 output:
BOOL (FALSE)
BOOL (FALSE)
Int (0)
NOTICE:A non well formed numeric value encountered in/tmp/test.php on line 5
String (3) "Foo"
4. Functions removed in PHP7
The list of functions removed is as follows:
Call_user_func () and Call_user_func_array () were discarded from PHP 4.1.0.
The deprecated Mcrypt_generic_end () function has been removed, use Mcrypt_generic_deinit () instead.
Obsolete MCRYPT_ECB (), MCRYPT_CBC (), MCRYPT_CFB (), and MCRYPT_OFB () functions have been removed.
Set_magic_quotes_runtime (), and its alias Magic_quotes_runtime () have been removed. They have been deprecated in PHP 5.3.0 and have lost functionality in PHP 5.4.0 due to the abandonment of magic quotes.
The deprecated set_socket_blocking () function has been removed, use stream_set_blocking () instead.
DL () is no longer available in PHP-FPM and is still available in the CLI and embed Sapis.
The following functions are removed from the GD Library: Imagepsbbox (), Imagepsencodefont (), Imagepsextendfont (), Imagepsfreefont (), Imagepsloadfont (), IMAGEPSS Lantfont (), Imagepstext ()
In configuration file php.ini, Always_populate_raw_post_data, Asp_tags, xsl.security_prefs are removed.
5. Objects created by the new operator cannot be assigned to variables by reference
The object created by the new operator cannot be assigned a value to a variable by reference
<?php
Class C {}
$c =& new C;
?>
PHP5 output:
Deprecated:assigning The return value of new by reference was Deprecated in/tmp/test.php on line 3
PHP7 output:
Parse error:syntax error, unexpected ' new ' (t_new) in/tmp/test.php on line 3
6. Remove ASP and script PHP tags
The way to differentiate PHP code using a tag like ASP and a script tag is removed. The affected tags are: <%%>, <%=%>, <script language= "PHP" > </script>
7. Initiating a call from an unmatched context
Statically invoking a non-static method in a mismatched context is deprecated in PHP 5.6, but in PHP 7.0 it causes the undefined $this variable in the called method and a warning that the behavior has been deprecated.
<?php
Class A {
Public Function test () {var_dump ($this);}
}
Note: There is no inheritance from class A
Class B {
Public Function Callnonstaticmethodofa () {a::test ();}
}
(New B)->callnonstaticmethodofa ();
?>
PHP5 output:
Deprecated:non-static method A::test () should not being called statically, assuming $this from incompatible context in/tmp/ Test.php on line 8
Object (B) #1 (0) {
}
PHP7 output:
Deprecated:non-static method A::test () should not being called statically in/tmp/test.php on line 8
notice:undefined variable:this in/tmp/test.php on line 3
Null
8, when the value overflow, the internal function will fail
When you convert a floating-point number to an integer, if the floating-point value is too large to be expressed as an integer, in the previous version, the intrinsic function truncates the integer directly and does not raise an error. In PHP 7.0, if this happens, a e_warning error is thrown and NULL is returned.
9. JSON extension has been replaced by Jsond
The JSON extension has been superseded by the jsond extension. For numerical processing, there are two points to note: First, the number cannot be a dot (. ) Ends (for example, a value of 34. Must write 34.0 or 34). Second, if you use scientific notation to denote numeric values, E must not be preceded by a dot (. (for example, 3.e3 must write 3.0e3 or 3e3).
10. The # comment format is removed from INI file
Comment Lines starting with # are no longer supported in the configuration file INI file, please use; (semicolon) to indicate a comment. This change applies to php.ini and files that are processed with the Parse_ini_file () and parse_ini_string () functions.
11, $HTTP _raw_post_data is removed
$HTTP _raw_post_data variable is no longer available. Please use Php://input as an alternative.
12. Yield changed to right join operator
When using the yield keyword, parentheses are no longer needed, and it is changed to the right join operator, whose operator priority is between print and-=. This can lead to changes in the behavior of existing code. You can eliminate ambiguity by using parentheses.
<?php
Echo yield-1;
In previous versions, it was interpreted as:
Echo (yield)-1;
Now, it will be interpreted as:
Echo Yield (-1);
Yield $foo or die;
In previous versions, it was interpreted as:
Yield ($foo or die);
Now, it will be interpreted as:
(yield $foo) or die;
?>
Php
PHP 7 test Case (RPM)