New features of PHP7

Source: Internet
Author: User
Tags hhvm intl parse error script php
The best language has released a new version, an epoch Big version: PHP7. PHP7 fixes a large number of bugs and adds features and syntactic sugar. These changes involve familiar and unfamiliar core functions and extensions such as core packages, GD libraries, PDO, ZIP, and ZLIB. PHP7 removed obsolete functions... the best language to release a new version, an epoch Big version: PHP7.

PHP7 fixes a large number of bugs and adds features and syntactic sugar. These changes involve familiar and unfamiliar core functions and extensions such as core packages, GD libraries, PDO, ZIP, and ZLIB.

PHP7 removed obsolete functions. for example, mysql _ series functions are discarded in PHP5.5 and deleted in PHP7.

PHP7 has higher performance than HHVM. It is twice that of PHP5.6.

# On April 9, December 3, the PHP development team announced that PHP 7.0.0 will be available soon. This release marks the beginning of an important new PHP 7 series. PHP 7.0.0 comes with a new version of Zend Engine, with numerous improvements and new features, such as performance improvement: PHP 7 up to double Fast PHP 5.6 significantly reduces memory usage abstract syntax tree consistent 64-bit support improved exception hierarchies many convert to abnormal fatal error security random number generator delete old and not supported SAPIs and extended null merge operator (?) Return and scalar type declaration anonymous class zero-cost assertion this is the next major version of PHP. Its release is the result of the development journey in the past two years. This is a special achievement of the core team. Moreover, it is the result of incredible efforts by many active community members. In fact, this is the rise and great potential of a new PHP generation. Congratulations! this is a spectacular PHP world! Thanks to all the contributors and supporters!

Based on the update log, I sorted out the involved class libraries: core, CLI_server, COM, Curl, Date, DBA, DOM, EXIF, Fileinfo, Filter, FPM, FTP, GD, GMP, hash, IMAP, Intl, JSON, LDAP, LiteSpeed, libxml, Mcrypt, Mysqli, OCI8, ODBC, Opcache, OpenSSL, Pcntl, PCRE, PDO, Baidu, PDO_mysql, Baidu, PDO_pgsql, Phar, Phpdbg, Reflection, Session, OAP, SPL, SQLite3, tandard, Streams, Tokenizer, XMLReader, XMLRPC, XSL, Zlib, Zip

I. PHP7's past and present

The following is an excerpt from and modified with laruence

PHP7 started the Spring Festival in 2014, because the PHP-5.5-based Opcache JIT was put on hold because it could not get the expected, and let laruence and others realize that the basic part is not good enough, and it cannot support JIT well, therefore, the reconstruction project was started, hoping to be improved by more than 30%. Later, we found that the performance was much higher than we thought, and we named it the php ng project.

After the vote, most people supported the php ng project and decided to develop the new version of PHP based on php ng. PHP6 was developed in the community, and its features were gradually implemented in PHP5.5 and 5.6, so PHP6 was put on hold. After a community vote, the new project is named PHP7.

Over the past two years, new features have been added, performance has been continuously improved, and many unreasonable improvements have been made to PHP7, making PHP7 more and more plump. from the underlying ZVAL change to the scalar type prompt, from the initial 30% performance improvement to the current performance leap of more than 100%, every change is worth looking forward. then, after several reluctant jumps, it will be displayed in front of you.

II. Installation

Installation: We have compiled core packages and PDO, GD, mysqli, Zip, etc.

>$ ./configure --prefix=/usr/local/php7 --enable-fpm --with-zlib --enable-mbstring --with-openssl --with-mysqli --with-mysql-sock --with-gd --enable-gd-native-ttf  --enable-pdo --with-pdo-mysql --with-gettext --with-curl --with-pdo-mysql --enable-sockets --enable-bcmath --enable-xml --with-bz2 --enable-zip -enable-pcntl>$ make>$ sudo make install

1. Test Case 1:

Generate 0.5 million arrays and query whether 0.5 million keys exist

 

The test results are as follows:

Compile time php test. php

Php test. php

0.60 s user

0.05 s system

98% cpu

0.667 total

Export time/usr/local/php7/bin/php test. php

/Usr/local/php7/bin/php test. php

0.05 s user

0.02 s system

92% cpu

0.073 total

PHP7 is 9 times faster than PHP5.5

2. Test Case 2:

Generate 0.5 million arrays and check whether 0.5 million values exist

 

Compile time php test. php

Php test. php

0.79 s user

0.01 s system

99% cpu

0.809 total

Export time/usr/local/php7/bin/php test. php

/Usr/local/php7/bin/php test. php

0.08 s user

0.01 s system

97% cpu

0.091 total

PHP7 is 8.7 times faster than PHP5.5

3. Test Case 3:

Examples and results are taken from the blog of laruence. Test PHP7 and HHVM3.2 based on Wordpress. Use Apache AB testing tool. 100 concurrent requests and 10000 requests. 100 requests are pushed before the test.

The results of PHP7 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 secondd: 258.22 [#/sec] (mean)

Time per request: 387.260 [MS] (mean)

Time per request: 3.873 [MS] (mean, internal SS all concurrent requests)

Transfer rate: 2251.64 [Kbytes/sec] canceled ed

HHVM-3.2

The result of HHVM is 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 secondd: 230.97 [#/sec] (mean)

Time per request: 432.957 [MS] (mean)

Time per request: 4.330 [MS] (mean, internal SS all concurrent requests)

Transfer rate: 2013.31 [Kbytes/sec] canceled ed

PHP7-258.22 qps hhvm-230.97 QPS

IV. new feature 1. scalar type declaration

There are two modes: forced (default) and strict mode. You can now use the following types of parameters (either in forced mode or in strict mode): string, integer (int), floating point number (float), and Boolean value (bool ). They expand other types introduced in PHP5: class names, interfaces, arrays, and callback types. In earlier versions, function parameter declarations can only be (Array $ arr) and (CLassName $ obj). basic types such as Int and String cannot be affirmed.

 

If no forced type conversion is performed, int (1) bool (true) is input ). After conversion, bool (true) is output)

2. return value type declaration

PHP 7 adds support for the return type declaration. The return type declaration specifies the type of the function return value. The available types are the same as those available in the parameter declaration.

 

The above routine will output:

Array

(

[0] => 6

[1] => 15

[2] => 24

)

3. null merge operator

A large number of ternary expressions and isset () are used in the project. The null merge operator (?) is added (??) This syntactic sugar. If the 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 version: $ _ GET ['id']? 'Err ';

4. Spacecraft operators (composite comparison operators)

The spacecraft operator is used to compare two expressions. If $ a is less than, equal to, or greater than $ B, it returns-1, 0, or 1. The comparison principle is based on the conventional comparison rules of PHP.

   1; // 0echo 1 <=> 2; // -1echo 2 <=> 1; // 1// Floatsecho 1.5 <=> 1.5; // 0echo 1.5 <=> 2.5; // -1echo 2.5 <=> 1.5; // 1// Stringsecho "a" <=> "a"; // 0echo "a" <=> "b"; // -1echo "b" <=> "a"; // 1?>
5. define a constant array through define ()
  
6. anonymous class

Currently, an anonymous class can be instantiated using the new class, which can be used to replace some complete class definitions that are "immediately burned.

  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 hexadecimal Unicode codepoint and prints a string in UTF-8 encoding format enclosed by a double quotation mark or heredoc. It can accept any valid codepoint, and the 0 at the beginning can be omitted.

  

Old output: u {9876}

New version input: top

8. Closure: call ()

Closure: call () now has better performance. it is short and competent to temporarily bind a method to the Closure of the object and call it.

  Name ;}; $ name =$ getNameFunc-> bindTo (new Test, 'test'); echo $ name (); // PHP7 is acceptable. PHP5.6 reports an error $ getX = function () {return $ this-> name ;}; echo $ getX-> call (new Test );
9. provide filtering for unserialize ()

This feature aims to provide a safer way to unpackage unreliable data. It uses a whitelist to prevent potential code injection.

  False]); // divide all objects into _ PHP_Incomplete_Class objects except 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 aims to expose more ICU functions. This class defines many static methods used to operate unicode characters in multiple character sets. Intl is the Pecl extension, need to be compiled into PHP before use, can also be apt-get/yum/port install php5-intl

  

The above routine will output:

10 ffff

COMMERCIAL

Bool (true)

11. expectation

It is expected to use both the backward and enhance the previous assert () method. It enables the use of assertions in the production environment to zero cost, and provides the ability to throw a specific exception when the assertions fail. The old version of the API will continue to be maintained for compatibility purposes. assert () is now a language structure, which allows the first parameter to be an expression, it is not just a string to be calculated or a boolean to be tested.

  

The above routine 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 at one time using a single use statement.

  
13. intp ()

Receive two parameters as the divisor and divisor, and return the integer part of the result of their division.

  

Output int (3)

14. CSPRNG

Two new functions are added: random_bytes () and random_int (). encrypted production of protected integers and strings. In short, random numbers have become safe.

Random_bytes-encrypted survival protected pseudo-random string

Random_int-encrypted pseudo-random integers protected for survival

15. preg_replace_callback_array ()

A new function preg_replace_callback_array () is added, which makes code more elegant when preg_replace_callback () is used. Before PHP7, the callback function calls every regular expression, and the callback function is contaminated on some branches.

16. Session options

Now, the session_start () function can receive an array as a parameter and overwrite the session configuration items in php. ini.

For example, you can set cache_limiter to private and disable it immediately after reading the session.

   'private',    'read_and_close' => true,]);?>
17. generator return value

Introduce the generator concept in PHP5.5. The generator function obtains the value of the yield identifier every time it is executed. In PHP 7, after the generator iteration is complete, you can obtain the return value of the generator function. Use Generator: getReturn.

  getReturn();?>

Output: 1 2 3

18. introduce other generators into the generator

You can introduce another or several generators in the generator. you only need to write yield from functionName1.

  

Output: 1 2 3 4 5 6

5. incompatibility 1. foreach no longer changes the internal array pointer

Before PHP 7, when the array is iterated through foreach, the array pointer will move. For more information, see the following code.

  

PHP5 output:

Int (1)

Int (2)

Bool (false)

PHP 7 output:

Int (0)

Int (0)

Int (0)

2. foreach has better iteration characteristics by referencing the time history

When referencing arrays, foreach can better track changes in iterations. For example, to add an iteration value to an array in an iteration, refer to the following code:

  

PHP5 output:

Int (0)

PHP 7 output:

Int (0)

Int (1)

3. a hexadecimal string is no longer considered a number.

A hexadecimal string is no longer considered a number.

  

PHP5 output:

Bool (true)

Bool (true)

Int (15)

String (2) "oo"

PHP 7 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. removed functions in PHP 7

The list of removed functions is as follows:

Call_user_func () and call_user_func_array () are discarded from PHP 4.1.0.

The discarded 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 are deprecated in PHP 5.4.0 due to magic quotes.

The obsolete set_socket_blocking () function has been removed. use stream_set_blocking () instead.

Dl () is no longer available in the PHP-FPM and is still available in CLI and embed SAPIs.

The following functions in the GD library are removed: imagepsbbox (), imagepsencodefont (), imagepsextendfont (), imagepsfreefont (), imagepsloadfont (), imagepsslantfont (), imagepstext ()

In the configuration file php. ini, always_populate_raw_post_data, asp_tags, and 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 the variable as a reference.

  

PHP5 output:

Deprecated: Assigning the return value of new by reference is deprecated in/tmp/test. php on line 3

PHP 7 output:

Parse error: syntax error, unexpected 'new' (T_NEW) in/tmp/test. php on line 3

6. removed ASP and script PHP labels

ASP-like labels and script labels are used to distinguish PHP code from each other. The affected labels are: <%>, <% = %>,

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.