Introduction to new features of PHP7

Source: Internet
Author: User
Tags ereg parse error scalar

  • About PHP
      • The development history of the 20;

      • The most popular web development language to date;

      • More than 82% of websites use PHP as their service-side development language;

    Introduction to New features
      • PHP Ng–zend Engine 3

      • Abstract syntax Tree

      • 64-bit INT support

      • Unified variable Syntax

      • New Closure::call ()

      • Consistency foreach Loop

      • Support for anonymous classes

      • New,, <=> ** ?? , \u{xxxx} operator

      • Added declaration of return type

      • Added a scalar type of declaration

      • Core errors can be caught by exception

      • Added context-sensitive lexical analysis

    PHP NG
      • Zval

    Size reduced from 24 bytes to 16 bytes

      • Zend Array (HashTable)

    Hashtable size reduced from 72 bytes to 56 bytes
    HashTable bucket size reduced from 72 bytes to 32 bytes

      • Optimization of function calls

      • Use of new memory allocation, management methods, reduce the waste of memory

      • Immutable array optimization

        $arr = [];for($i=0; $i<100000; $i++) { $arr[] = [‘php‘];}p(memory_get_usage(true));

    PHP5:45M
    PHP7:10M

      • Some very common, less expensive functions become the engine-backed opcode directly.

    call_user_function(_array)=ZEND_INIT_USER_CALL
    is_int, is_string , is_array 、... =ZEND_TYPE_CHECK
    strlen=ZEND_STRLEN
    defined=ZEND+DEFINED

      • Optimization of core sequencing

    PHP5 ( zend_qsort )
    Quick sort (non-stable sort)

    array(1 => 0, 0 => 0)

    PHP7 ( zend_sort )
    Quick Sort + Select sort (Stable sort)

    array(0 => 0, 1 => 0)

    Use select sort less than 16 elements, greater than 16 to split by 16 units, use Select Sort, and then all together to use quick sort. Compared to the previous, the internal elements from the unstable sort into a stable sort, reduce the number of exchange of elements, reduce the number of memory operations, performance increased by 40%

    Abstract syntax Tree

    If we have such a demand now, to PHP source files on the line syntax detection, implementation code specification. PHP5 before the words, no AST, directly from the parser generated opcodes! Need to use some external PHP syntax parser to implement, and PHP7 added AST, we can implement such an extension ourselves, using the extension provided by the function can directly get the file corresponding to the AST structure, and this structure is what we can recognize, So we can do some optimization and judgment on this basis.

    64-bit INT support
      • Support for storing strings larger than 2GB

      • Supports uploading files larger than 2GB in size

      • Guaranteed string "64-bit" is 64bit on all platforms

    Unified syntax Variables
    $$foo[‘bar‘][‘baz‘] 

    PHP5:${$foo[‘bar’][‘baz‘]}
    PHP7: ($$foo)[‘bar’][‘baz‘] "rule from left to right"

    (function() {})();
    $foo()();
    [$obj, ‘method‘]();class A {    public static function a1() {}}[new A, ‘a1‘]();
    New Closure::call ()
    $f = function() {    p($this->name);};class F { private $name = ‘F‘;}$f->call(new F);
    Support for anonymous classes
    function getAnonymousClass($config) {    return new class(config) {}; }p(getAnonymousClass(array()));
    A consistent foreach Loop
    PHP5$a = Array (1,2,3);foreach ($a as$v) {Var_dump (current ($a));}int2)int2)int2)$a = Array (1,2,3);$b =&$a;foreach ($a as$v) {Var_dump (current ($a));}int2)int3) bool (FALSE)$a = Array (1,2,3);$b =$a;foreach ($a as$v) {Var_dump (current ($a));}int1)int1)int1)//PHP7: The internal pointer to the data is no longer operational$a = Array (1,2,3);foreach ($a as$v) {Var_dump (current ($a))}int1)int1)int1)$a = Array (1,2,3);$b =&$a;foreach ( $a as  $v) {Var_dump (current ($ A) int (1) int ( 1) int (1)  $a = Array (1, 2, 3);  $a;  $a as  $v) {Var_dump (current (  $a))} int (1) int ( 1) int (1)          
    A few new operators

    <=>

    //php5function compare $a,  $b) { Span class= "Hljs-keyword" >return ( $a <  $b)?-1: (( $a > $b)? 1: 0);} //php7function compare $a,  $b) { Span class= "Hljs-keyword" >return  $a <=>  $b;}    

    **

    2 ** 2; // 2 * 2 = 42 ** -1; // 1 / 2 = 0.53 ** -2; // 1 / 9 = 0.111111111

    ??

    $a = null;$b = 1;$c = 2;echo $a ?? $b , ‘,’ , $c ?? $b; // 1,2echo $a ?? $b ?? $c , ‘,’ , $a ?? $d ?? $c; // 1,2

    \U{XXXX}

    echo "\u{4f60}";//你echo "\u{65b0}";//新// 从右至左强制echo"\u{202E}iabgnay\u{1F602}";;? yangbai
    Declaration of the return type
    function getInt() : int { return ‘test‘;}; getInt();//返回值为DateTime的函数function getDateTime() : DateTime { return new DateTime();}; 
    Declaration of scalar types
    function getAmount(int $num) : int { return $num;}; getAmount(‘test‘);//PHP5#PHP Catchable fatal error: Argument 1 passed to getInt() must be an instance of int, string given…//PHP7#Fatal error: Uncaught TypeError: Argument 1 passed to getInt() must be of the type integer, string given…getAmount(‘123‘);#PHP7新增的严格模式选项开启下也会报错【declare(strict_types=1),注意要放到代码的第一行】
    The core error can be caught by an exception
    try {    non_exists_func();} catch(EngineException $e) {    echo "Exception: {$e->getMessage();}\n";} finally { echo "undefined function…";}//这里用php7试了一下没有捕获成功【但是确实抛出了异常】。。。#Exception: Call to undefined function non_exists_func()
    A sensitive lexical analysis of the upper and lower questions
    PHP5ClassCollection {PublicfunctionForeach($arr) {}}#Parse error:parse error, expecting ' "identifier (t_string)" ' ...PHP7ClassCollection {PublicfunctionForeach($arr) {Return$this; }PublicfunctionInch ( $arr) {return  $this; } public function sort $condition) { return  $this;} public function echo $condition) { return  ' OK ';}}  $collection = new collection ();  $collection->in ()->foreach ()->sort ()->echo ();          
    Breaking some of the things
      • MySQL, Ereg

    MySQL moved to the EXT/PECL, Ereg moved to Ext/pcre.

    • ISAPI, Tux etc Sapis

    • <? and <? Language= "PHP" such as the label was removed

    • HTTP_RAW_POST_DATARemoved (can use php://input overrides)

    • $o = & new className(), and no longer support such a notation

    • mktime(), gmmktime() the parameters of the function $is_dst are removed

    • setlocale()Function $category argument does not support string, must be a constant at the beginning of the LC

    • php.ini file removed # as a comment, unified with; go to comment

    • function definition parameter with the same name does not support

    • Class with the same name constructor is not recommended (not currently removed and will be removed later)

    • String, int and float Such keywords cannot be used as classes, interfaces, trait names

    • func_get_arg/ func_get_args Gets the value of the current variable

    • Invalid octal number generates a compilation error

    • preg_replace()Matching mode is no longer supported/e

    • 16 binary string number conversion is removed

    • Non-static calls that statically invoke an incompatible context are no longer supported $this

    • Unsafe Curl file uploads (use Curlfile instead)

      //PHP5curl_setopt(ch, CURLOPT_POSTFIELDS, array(    ‘file‘ => ‘@‘.realpath(‘image.png‘), )); //PHP7curl_setopt(ch, CURLOPT_POSTFIELDS, [ ‘file‘ => new CURLFile(realpath(‘image.png‘)), ]); 
    • Some of the removed functions and options

      Set_magic_quotes_runtime (); Magic_quotes_runtime ();//(Use Stream_set_blocking () instead) set_socket_blocking ();//(Use Mcrypt_generic_deinit () instead) mcrypt_generic_end ();//(Use Mcrypt_encrypt ()and Mcrypt_decrypt () instead) MCRYPT_ECB (); MCRYPT_CBC (); MCRYPT_CFB (); MCRYPT_OFB ();//(Use Datefmt_set_timezone ()or Intldateformatter::settimezone () instead) datefmt_set_timezone_id (); Intldateformatter::settimezoneid ();//( Use xsltprocessor::setsecurityprefs () instead) Xsl.security_prefs;//php.ini//(Usephp.input_encoding, Php.internal_encoding and php.output_encoding instead) iconv.input_encoding;iconv.output_encoding; iconv.internal_encoding;mbstring.http_input;mbstring.http_output;mbstring.internal_encoding; (UsePDO::ATTR_ Emulate_prepares instead) PDO::P gsql_attr_disable_native_prepared_statement;//driver option//(Usepeer_name instead) Cn_match;//ssl context options Sni_server_name;//ssl context options     

Introduction to new features of PHP7

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.