This section analyzes the new functions and syntax changes of PHP 7 and the new functions of PHP 7. The new functions and syntax changes of PHP 7 are summarized. The new functions of PHP 7 have two syntax scalar type declarations: mandatory (default) and strict. Now you can use the following types of parameters (no analysis of new functions and syntax changes in PHP7 summary, analysis of new functions of php7 syntax
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};?>
Intp ()
Receive two parameters as the divisor and divisor, and return the integer part of the result of their division.
<?phpvar_dump(intp(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: <%>, <% = %>,