Analysis of new functions and syntax changes in PHP 7, analysis of new function syntax in PHP 7

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

Analysis of new functions and syntax changes in PHP 7, analysis of new function syntax in PHP 7

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 ). In earlier versions, the parameter declaration of a function can only be (Array $ arr) or (CLassName $ obj). Basic types such as Int and String cannot be declared.

<?phpfunction check(int $bool){var_dump($bool);}check(1);check(true);

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

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.

<?phpfunction arraysSum(array ...$arrays): array{return array_map(function(array $array): int {return array_sum($array);}, $arrays);}print_r(arraysSum([1,2,3], [4,5,6], [7,8,9]));

The above routine will output:

Array([0] => 6[1] => 15[2] => 24)

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, the second operand is returned.

Old Version: isset ($ _ GET ['id'])? $ _ GET [id]: err;

New Version: $ _ GET ['id']? 'Err ';

Spacecraft operator (composite comparison operator)

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

Use define () to define a constant Array

<?phpdefine('ANIMALS', ['dog', 'cat', 'bird']);echo ANIMALS[1]; // outputs "cat"

Anonymous class

Now an anonymous class can be instantiated using new class.

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

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.

<?phpecho “\u{9876}”

Old output: \ u {9876}

New Version input: Top

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.

<? Phpclass Test {public $ name = "lixuan";} // both PHP7 and PHP5.6 can be $ getNameFunc = function () {return $ this-> 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 );

Provides Filtering for unserialize ()

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

<? Php // divide 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, which is the same as unserialize ($ foo) $ data = unserialize ($ foo, ["allowed_classes" => true]);

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

<?phpprintf('%x', IntlChar::CODEPOINT_MAX);echo IntlChar::charName('@');var_dump(IntlChar::ispunct('!'));

The above routine will output:

10 ffff
COMMERCIAL
Bool (true)

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.

<?phpini_set('assert.exception', 1);class CustomError extends AssertionError {}assert(false, new CustomError('Some error message'));

The above routine 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 at one time using 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; // use some \ namespace \ {ClassA, ClassB, ClassC as C} After PHP7; use function some \ namespace \ {fn_a, fn_ B, fn_c}; use con St some \ namespace \ {ConstA, ConstB, ConstC};?>

Intdiv ()

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

<?phpvar_dump(intdiv(7, 2));

Output int (3)

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

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.

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.

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

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.

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

Introduce other generators to the generator

You can introduce another or several generators in the generator. You only need to 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

Incompatible

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.

<?php$array = [0, 1, 2];foreach ($array as &$val) {var_dump(current($array));}

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:

<?php$array = [0];foreach ($array as &$val) {var_dump($val);$array[1] = 1;}

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.

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

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.

<?phpclass C {}$c =& new C;

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: <%>, <% = %>, and <script language = "php"> </script>

7. Initiate a call from an unmatched Context

The non-static method is called in a static manner in the context of the mismatch. It is discarded in PHP 5.6. However, in PHP 7.0, the $ this variable is not defined in the called method, and warnings that have been discarded.

<? Phpclass A {public function test () {var_dump ($ this) ;}}// Note: class B {public function callNonStaticMethodOfA () {:: test () ;}} (new B)-> callNonStaticMethodOfA ();

PHP5 output:

Deprecated: Non-static method A::test() should not be called statically, assuming $this from incompatible context in /tmp/test.php on line 8object(B)#1 (0) {}

PHP 7 output:

Deprecated: Non-static method A: test () shocould not be 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 overflows, 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, the internal function directly truncates the integer in the previous version, it does not cause errors. In PHP 7.0, if this happens, the E_WARNING error is thrown and NULL is returned.

9. JSON extensions have been replaced by JSOND

The JSON extension has been replaced by the JSOND extension. For the processing of numerical values, there are two points to note: first, the numerical value cannot end with a period (.) (for example, the numerical value 34. Must write 34.0 or 34 ). Second, if scientific notation is used to represent a value, e must be preceded by a period (.) (for example, 3. e3 must be written as 3.0e3 or 3e3)

10. # The annotation format is removed from the INI file.

Note lines starting with # are no longer supported in the configuration file ini. Use; (semicolon) to indicate comments. This change applies to php. ini and files processed using the parse_ini_file () and parse_ini_string () functions.

11. $ HTTP_RAW_POST_DATA is removed.

The $ HTTP_RAW_POST_DATA variable is no longer provided. Use php: // input as an alternative.

12. Change yield to the right join operator.

When the yield keyword is used, parentheses are no longer needed and it is changed to the right join operator. The operator priority is between print and =>. This may change the behavior of the existing code. Parentheses can be used to eliminate ambiguity.

<? Phpecho yield-1; // in earlier versions, it will be interpreted as: echo (yield)-1; // now, it will be interpreted as: echo yield (-1 ); yield $ foo or die; // in earlier versions, it will be interpreted as: yield ($ foo or die); // now, it will be interpreted as :( yield $ foo) or die;

The above is a summary of the new functions and syntax changes of PHP 7 introduced by xiaobian. I hope it will be helpful to you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

Related Article

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.