Brief analysis on new functions and grammatical changes of PHP7

Source: Internet
Author: User
Tags deprecated intl script php

There are two modes of scalar type declarations: 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 a Boolean value (BOOL). In older versions, the function's argument declarations can only be (Array $arr), (CLassName$objetc, basic types such as int,string are not able to be declared<?PHPfunctionCheck (int$bool){Var_dump($bool);} Check (1); Check (trueIf no coercion type is cast, an int is entered (1) BOOL (true)。 The conversion will output bool (true) BOOL (true) return value type declaration PHP7added 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. <?PHPfunctionArrayssum (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] = 24the null merge operator in the project has a large number of simultaneous use of ternary expressions andisset(), a null merge operator (??) is added.) this grammatical sugar. If a variable exists and the value is not NULL, it returns its own value, otherwise the second operand is returned. Old version:isset($_get[' ID ']) ? $_get[id]: Err; NEW: $_get[' id ']?? ' Err 'spaceship operator (combination comparator) The spaceship operator is used to compare two expressions. When $ A is less than, equal to, or greater than $b, it returns 1, 0, or 1<?php//integersecho 1 <=> 1 respectively; 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?> defines a constant array <?phpdefine by define () (' ANIMALS ', [' dog ', ' cat ', ' bird ']); Echo Animals[1]; The outputs "cat" anonymous class now supports instantiating an anonymous class with the new class <?phpinterface Logger {public Function log (string $msg);} Class Application {Private $logger;p ublic 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 ()); Unicode codepoint translation Syntax This accepts a Unicode codepoint in the form of 16, and prints a double-quote or heredoc-enclosed string in UTF-8 encoded format. Any valid codepoint can be accepted, and 0 of the beginning can be omitted. <?phpecho "\u{9876}" legacy output: \u{9876} New input: Top Closure::call () Closure::call () now has better performance, short and able to temporarily bind a method to the object on the closure and call it < Phpclass test{public $name = "Lixuan";} Both PHP7 and PHP5.6 can $getnamefunc = function () {return $this->name;}; $name = $getNameFunc->bindto (new Test,' Test '); Echo $name ();//php7 Yes, PHP5.6 error $getx = function () {return $this->name;}; Echo $getX->call (new Test), which provides filtering for unserialize () is designed to provide a more secure way to unpack 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]);//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]); Intlchar New added The 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<?phpprintf ('%x ', Intlchar::codepoint_max); Echo Intlchar::charname (‘@‘); Var_dump (Intlchar::ispunct (‘!‘) ; The above routines output: 10ffffCOMMERCIAL Atbool (true) expected to be used backwards and to enhance the previous assert () method. 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. <?phpini_set (‘assert.Exception‘, 1), class Customerror extends Assertionerror {}assert (False, new Customerror (' Some error message '); The above routines output: Fatal error:uncaught customerror:some error Messagegroup use declarations classes, functions, and constants imported from the same namespace can now be passed through a single US The e statement was imported at once. &LT;?PHP//PHP7 before 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;//PHP7 after 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};? >intdiv () receives two parameters as dividend and divisor, returning the integer portion of the result of their division. <?phpvar_dump (Intdiv (7, 2)); output int (3) csprng adds two functions: Random_bytes () and Random_int (). Production-protected integers and strings that can be encrypted. My crappy translation, in short, the random number becomes safe. random_bytes-encryption survives the protected pseudo-random string random_int-encrypts the surviving protected pseudo-random integer Preg_replace_callback_array () A new function is added Preg_replace_callback_ Array (), which allows the code to become 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. Session options Now, the Session_Start () function can receive an array as a parameter, you can overwrite the configuration entry for the session in PHP.ini. For example, set the Cache_limiter to private and close <?phpsession_start immediately after reading the session ([' Cache_limiter ' = 'Private‘,' Read_and_close ' = = True,]); The generator's return value introduces the concept of the generator 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 (). <?phpfunction Generator () {yield 1;yield 2;yield 3;return "a";} $generatorClass = ("generator") (), foreach ($generatorClass as $val) {echo $val. “;} echo $generatorClass->getreturn (); output: 1 2 3 A The introduction of other generators in the generator can introduce another or several generators in the builder, just write yield from functionname1< Phpfunction 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 incompatibility 1, foreach no longer changes the internal array pointer before PHP7, and when the array passes through the 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 a better iterative behavior when iterating through the array using references, now the 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: <?php$array = [0];foreach ($array as & $val) {var_dump ($val); $array [1] = 1;} PHP5 output: Int (0) PHP7 output: Int (0) int (1) 3, hexadecimal string is no longer considered a number with a hexadecimal string is no longer considered a digital <?phpvar_dump ("0x123" = = "291"); Var_dump (Is_ Numeric ("0x123")), Var_dump ("0xe" + "0x1"), Var_dump ("foo", "0x1"); PHP5 output: BOOL (TRUE) bool (true) Int (page) 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 5string (3) "Foo" 4, PHP7 removed function list as follows: Call_user_func () and CALL_USER_FUNC_ Array () is deprecated 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 (), Imagepsslantfont (), Imagepstext () in the configuration file php.ini, Always_populate_raw_post_data, Asp_tags, xsl.security_prefs are removed. 5. NewAn object created by an operator cannot be assigned to a variable by reference to an object created by the new operator cannot be referenced to a variable <?phpclass c {} $c =& new C; PHP5 output: Deprecated:assigning The return value of new by reference was Deprecated in/tmp/test.php on line 3PHP7 output: Parse err  Or:syntax Error, unexpected‘New‘ (t_new) in/tmp/test.php on line 36, the removal of ASP and script PHP tags using asp-like tags, and script tags to differentiate PHP code is removed in the way. The affected tags are: <%%>, <%=%>, <script language= "php" > </script>7, invoking non-static methods statically in mismatched contexts from mismatched context-initiated calls has been deprecated in PHP 5.6, but in PHP 7.0 it will result in undefined $this variables in the called method, as well as warnings that this behavior has been deprecated. <?phpclass 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 I n/tmp/test.php on line 8object (B) #1 (0) {}PHP7 output: Deprecated:non-static method A::test () should not being called statically in/tmp/test.php on line 8notice:undefined variable:this in/tmp/test.php in line 3null8, when the value overflows, the intrinsic function fails to convert the floating-point number to an integer, such as 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. The JSON extension has been superseded by the Jsond extension by Jsond instead of the JSON extension. For numerical processing, there are two points to note: first, numberThe value cannot end with a dot number (.) (for example, the value 34. Must write 34.0 or 34). Second, if you use scientific notation to denote a numeric value, the E front must not be a dot (.) (for example, 3.e3 must write 3.0e3 or 3e3) 10, the INI file in the # comment format is removed in the profile INI file, the comment lines starting with # are no longer supported, use; (semicolon) to represent the 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 the right join operator when using the yield keyword, the parentheses are no longer required, 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. <?phpecho yield-1;//In previous versions will be interpreted as: echo (yield)-1;//now, it will be interpreted as: echo yield ( -1), yield $foo or die;//in previous versions will be interpreted as: yield ($foo or Die);//Now it will be interpreted as: (yield $foo) or die;

Brief analysis on new functions and grammatical changes 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.