Home > Article > Backend Development > A brief analysis of the new functions and syntax changes of PHP7, a brief analysis of the new function syntax of PHP7_PHP Tutorial
Scalar type declaration
There are two modes: mandatory (default) and strict mode. The following type parameters are now available (either in forced or strict mode): string, int, float, and bool. In the old version, function parameter declarations could only be (Array $arr), (CLassName $obj), etc. Basic types such as Int, String, etc. could not be declared
<?php function check(int $bool){ var_dump($bool); } check(1); check(true);
If there is no forced type conversion, int(1)bool(true) will be entered. After conversion, bool(true) bool(true)
will be outputReturn value type declaration
PHP 7 adds support for return type declarations. The return type declaration specifies the type of the function's return value. The available types are the same as those available in the parameter declaration.
<?php function 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 coalescing operator
There are a lot of cases where ternary expressions and isset() are used simultaneously in the project, and the syntactic sugar of null coalescing operator (??) is added. If the variable exists and is not NULL, it returns its own value, otherwise it returns the second operand.
Old version: isset($_GET['id']) ? $_GET[id] : err;
New version: $_GET['id'] ?? 'err';
Spaceship operator (combination comparison operator)
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 // Integers echo 1 <=> 1; // 0 echo 1 <=> 2; // -1 echo 2 <=> 1; // 1 // Floats echo 1.5 <=> 1.5; // 0 echo 1.5 <=> 2.5; // -1 echo 2.5 <=> 1.5; // 1 // Strings echo "a" <=> "a"; // 0 echo "a" <=> "b"; // -1 echo "b" <=> "a"; // 1 ?>
Define constant array through define()
<?php define('ANIMALS', ['dog', 'cat', 'bird']); echo ANIMALS[1]; // outputs "cat"
Anonymous class
Now supports instantiating an anonymous class through new class
<?php interface 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 Unicode codepoint in hexadecimal form and prints out a UTF-8 encoded string surrounded by double quotes or a heredoc. Any valid codepoint is accepted, and the leading 0 can be omitted.
<?php echo “\u{9876}”
Old version output: u{9876}
New version input: Like
Closure::call()
Closure::call() now has better performance, a short and concise way to temporarily bind a method to the closure of the object and call it
<?php class Test{public $name = "lixuan";} //PHP7和PHP5.6都可以 $getNameFunc = function(){return $this->name;}; $name = $getNameFunc->bindTo(new Test, 'Test'); echo $name(); //PHP7可以,PHP5.6报错 $getX = function() {return $this->name;}; echo $getX->call(new Test);
Provide filtering for unserialize()
This feature is designed to provide a safer way to unpack unreliable data. It prevents potential code injection through whitelisting.
<?php //将所有对象分为__PHP_Incomplete_Class对象 $data = unserialize($foo, ["allowed_classes" => false]); //将所有对象分为__PHP_Incomplete_Class 对象 除了ClassName1和ClassName2 $data = unserialize($foo, ["allowed_classes" => ["ClassName1", "ClassName2"]); //默认行为,和 unserialize($foo)相同 $data = unserialize($foo, ["allowed_classes" => true]);
IntlChar
The newly added IntlChar class is designed to expose more ICU functions. This class itself defines many static methods for manipulating unicode characters in multiple character sets. Intl is a Pecl extension and needs to be compiled into PHP before use. You can also apt-get/yum/port install php5-intl
<?php printf('%x', IntlChar::CODEPOINT_MAX); echo IntlChar::charName('@'); var_dump(IntlChar::ispunct('!'));
The above routine will output:
10ffff
COMMERCIAL AT
bool(true)
Expected
The intention is to use backwards and enhance the previous assert() method. It makes enabling assertions cost-effective in production and provides the ability to throw specific exceptions when assertions fail. The old version of the API will continue to be maintained for compatibility purposes, and assert() is now a language construct that allows the first argument to be an expression, not just a string to be calculated or a boolean to be tested.
<?php ini_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 once with a single use statement.
<?php //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; // PHP7之后 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, and returns the integer part of their division result.
<?php var_dump(intdiv(7, 2));
Output int(3)
CSPRNG
New two functions: random_bytes() and random_int(). Can encrypt and produce protected integers and strings. My poor translation, in short, random numbers have become safe.
random_bytes — Cryptographically protected pseudo-random strings
random_int — cryptographically protected pseudo-random integer
preg_replace_callback_array()
A new function preg_replace_callback_array() has been added. Using this function can make the code more elegant when using the preg_replace_callback() function. Before PHP7, the callback function would be called for every regular expression, and the callback function was contaminated on some branches.
Session options
Now, the session_start() function can receive an array as a parameter, which can override the session configuration items in php.ini.
For example, set cache_limiter to private and close the session immediately after reading the session
<?php session_start([ 'cache_limiter' => 'private', 'read_and_close' => true, ]);
The return value of the generator
The concept of generator is introduced in PHP5.5. Each time the generator function is executed, it gets a value identified by yield. In PHP7, when the generator iteration is completed, the return value of the generator function can be obtained. Obtained through Generator::getReturn().
<?php function generator() { yield 1; yield 2; yield 3; return "a"; } $generatorClass = ("generator")(); foreach ($generatorClass as $val) { echo $val.” “; } echo $generatorClass->getReturn();
The output is: 1 2 3 a
生成器中引入其他生成器
在生成器中可以引入另一个或几个生成器,只需要写yield from functionName1
<?php function 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, " "; }
输出:1 2 3 4 5 6
不兼容性
1、foreach不再改变内部数组指针
在PHP7之前,当数组通过 foreach 迭代时,数组指针会移动。现在开始,不再如此,见下面代码。
<?php $array = [0, 1, 2]; foreach ($array as &$val) { var_dump(current($array)); }
PHP5输出:
int(1)
int(2)
bool(false)
PHP7输出:
int(0)
int(0)
int(0)
2、foreach通过引用遍历时,有更好的迭代特性
当使用引用遍历数组时,现在 foreach 在迭代中能更好的跟踪变化。例如,在迭代中添加一个迭代值到数组中,参考下面的代码:
<?php $array = [0]; foreach ($array as &$val) { var_dump($val); $array[1] = 1; }
PHP5输出:
int(0)
PHP7输出:
int(0)
int(1)
3、十六进制字符串不再被认为是数字
含十六进制字符串不再被认为是数字
<?php var_dump("0x123" == "291"); var_dump(is_numeric("0x123")); var_dump("0xe" + "0x1"); var_dump(substr("foo", "0x1"));
PHP5输出:
bool(true)
bool(true)
int(15)
string(2) "oo"
PHP7输出:
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、PHP7中被移除的函数
被移除的函数列表如下:
call_user_func() 和 call_user_func_array()从PHP 4.1.0开始被废弃。
已废弃的 mcrypt_generic_end() 函数已被移除,请使用mcrypt_generic_deinit()代替。
已废弃的 mcrypt_ecb(), mcrypt_cbc(), mcrypt_cfb() 和 mcrypt_ofb() 函数已被移除。
set_magic_quotes_runtime(), 和它的别名 magic_quotes_runtime()已被移除. 它们在PHP 5.3.0中已经被废弃,并且 在in PHP 5.4.0也由于魔术引号的废弃而失去功能。
已废弃的 set_socket_blocking() 函数已被移除,请使用stream_set_blocking()代替。
dl()在 PHP-FPM 不再可用,在 CLI 和 embed SAPIs 中仍可用。
GD库中下列函数被移除:imagepsbbox()、imagepsencodefont()、imagepsextendfont()、imagepsfreefont()、imagepsloadfont()、imagepsslantfont()、imagepstext()
在配置文件php.ini中,always_populate_raw_post_data、asp_tags、xsl.security_prefs被移除了。
5、new 操作符创建的对象不能以引用方式赋值给变量
new 操作符创建的对象不能以引用方式赋值给变量
<?php class C {} $c =& new C;
PHP5输出:
Deprecated: Assigning the return value of new by reference is deprecated in /tmp/test.php on line 3
PHP7输出:
Parse error: syntax error, unexpected 'new' (T_NEW) in /tmp/test.php on line 3
6、移除了 ASP 和 script PHP 标签
使用类似 ASP 的标签,以及 script 标签来区分 PHP 代码的方式被移除。 受到影响的标签有:72637aecae1027e7d023ac098a170986、332000003288cabbdff89f9a8e5a919b、842e8e9dd470ac0da5d8b75be3525bf2 2cacc6d41bbb37262a98f745aa00fbf0
7、从不匹配的上下文发起调用
在不匹配的上下文中以静态方式调用非静态方法, 在 PHP 5.6 中已经废弃, 但是在 PHP 7.0 中, 会导致被调用方法中未定义 $this 变量,以及此行为已经废弃的警告。
<?php class A { public function test() { var_dump($this); } } // 注意:并没有从类 A 继承 class B { public function callNonStaticMethodOfA() { A::test(); } } (new B)->callNonStaticMethodOfA();
PHP5输出:
Deprecated: Non-static method A::test() should not be called statically, assuming $this from incompatible context in /tmp/test.php on line 8 object(B)#1 (0) { }
PHP7输出:
Deprecated: Non-static method A::test() should not be called statically in /tmp/test.php on line 8
Notice: Undefined variable: this in /tmp/test.php on line 3
NULL
8、在数值溢出的时候,内部函数将会失败
将浮点数转换为整数的时候,如果浮点数值太大,导致无法以整数表达的情况下, 在之前的版本中,内部函数会直接将整数截断,并不会引发错误。 在 PHP 7.0 中,如果发生这种情况,会引发 E_WARNING 错误,并且返回 NULL。
9、JSON 扩展已经被 JSOND 取代
JSON 扩展已经被 JSOND 扩展取代。 对于数值的处理,有以下两点需要注意的: 第一,数值不能以点号(.)结束 (例如,数值 34. 必须写作 34.0 或 34)。 第二,如果使用科学计数法表示数值,e 前面必须不是点号(.) (例如,3.e3 必须写作 3.0e3 或 3e3)
10、INI 文件中 # 注释格式被移除
在配置文件INI文件中,不再支持以 # 开始的注释行, 请使用 ;(分号)来表示注释。 此变更适用于 php.ini 以及用 parse_ini_file() 和 parse_ini_string() 函数来处理的文件。
11、$HTTP_RAW_POST_DATA 被移除
不再提供 $HTTP_RAW_POST_DATA 变量。 请使用 php://input 作为替代。
12、yield 变更为右联接运算符
在使用 yield 关键字的时候,不再需要括号, 并且它变更为右联接操作符,其运算符优先级介于 print 和 => 之间。 这可能导致现有代码的行为发生改变。可以通过使用括号来消除歧义。
<?php echo yield -1; // 在之前版本中会被解释为: echo (yield) - 1; // 现在,它将被解释为: echo yield (-1); yield $foo or die; // 在之前版本中会被解释为: yield ($foo or die); // 现在,它将被解释为: (yield $foo) or die;
以上所述是小编给大家介绍的浅析PHP7新功能及语法变化总结,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对帮客之家网站的支持!