Brief analysis of new functions and grammatical changes of PHP7, a brief analysis of PHP7 new functional Grammar _php tutorial

Source: Internet
Author: User
Tags deprecated intl parse error script php script tag

Brief analysis on the new function and grammatical changes of PHP7 and the new functional grammar of PHP7


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). In the older version, the function's parameter declaration can only be (Array $arr), (CLassName $obj), etc., basic types such as int,string, etc. are not able to be declared

<?phpfunction 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

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.

<?phpfunction 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)

Null merge operator

In the case of a large number of simultaneous use of ternary and isset () in the project, a new null merge operator (??) is added to this syntactic 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, respectively

<?php//Integersecho 1 <=> 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?>

Defining a constant array by define ()

<?phpdefine (' ANIMALS ', [' dog ', ' cat ', ' bird '), Echo animals[1]; Outputs "Cat"

Anonymous class

It is now supported to instantiate 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 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.

<?phpecho "\u{9876}"

Legacy output: \u{9876}

New input: Top

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

<?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);

Provides 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]);//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

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

<?phpprintf ('%x ', Intlchar::codepoint_max); Echo intlchar::charname (' @ '); Var_dump (intlchar::ispunct ('! '));

The above routines will output:

10ffff
Commercial at
BOOL (TRUE)

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.

<?phpini_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

Group Use declarations

Classes, functions, and constants imported from the same namespace can now be imported once with a single use statement.

<?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

Two new functions: 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.

random_bytes-encryption survival protected pseudo-random string

random_int-encryption survival protected pseudo-random integer

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.

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

<?phpsession_start ([' cache_limiter ' = ' private ', ' read_and_close ' = true,]);

The return value of the generator

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 ().

<?phpfunction 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

Introducing additional generators into the builder

You can introduce another or several generators in the generator, 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

Non-compatibility

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

<?phpvar_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 (), Imagepsslantfont (), 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

<?phpclass 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: <%%>, <%=%>,

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.

<?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 in/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 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 numeric handling, there are two points to note: First, the value cannot end with a dot (.) (for example, a value of 34. Must write 34.0 or 34). Second, if a numeric value is expressed using scientific notation, the E front must not be 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, use; (semicolon) to represent comments. 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.

<?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;

The above is a small series to introduce you to the analysis of PHP7 new functions and grammatical changes summary, I hope that we have some help, if you have any questions please give me a message, small series will promptly reply to you. Thank you very much for the support of our website!

http://www.bkjia.com/PHPjc/1136631.html www.bkjia.com true http://www.bkjia.com/PHPjc/1136631.html techarticle Brief analysis on new functions and grammatical changes of PHP7 PHP7 new features syntax scalar type declarations have two modes: mandatory (default) and strict mode. You can now use the following type parameters (None ...).

  • 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.