Home > Backend Development > PHP7 > body text

A quick summary of new features in PHP7

coldplay.xixi
Release: 2023-02-17 21:36:01
forward
1843 people have browsed it

A quick summary of new features in PHP7

Preface

This article is a summary of the lecture + follow-up research.
Speaking of following the fashion back then, I immediately installed php7 on my computer as soon as it came out. php5 and php7 coexisted. I immediately wrote a super time-consuming loop script and tested it. It is true that php7 is much more powerful, and then I paid some attention to it. New features and some discarded usage.
Since php upgrade is a top priority, the company only plans to upgrade in the near future, so I have been able to appreciate the pleasure brought by php7 in private. The friend in charge of the upgrade made a sharing, which is quite comprehensive. Mark it here. Take notes.

Recommended (free): PHP7

Main research questions:
1.Benefits brought by PHP7
2.PHP7 New things brought
3. Abandonment brought by PHP7
4. Changes brought by PHP7
5. How to give full play to the performance of PHP7
6. How to write better code to welcome PHP7?
7. How to upgrade the current project code to be compatible with PHP7?

Benefits of PHP7

Yes, The substantial improvement in performance can save machines and save money.
A quick summary of new features in PHP7

New things brought by PHP7

1. Type declaration.

You can use string (string), integer (int), floating point number (float), and Boolean value (bool) to declare the parameter type and function return value of the function.

declare(strict_types=1);function add(int $a, int $b): int {
    return $a+$b;
}

echo add(1, 2);
echo add(1.5, 2.6);
Copy after login

php5 cannot execute the above code. When php7 is executed, it will first output a 3 and an error (Argument 1 passed to add() must be of the type integer, float given);

There are two modes for scalar type declarations: mandatory (default) and strict mode.
declare(strict_types=1), must be placed on the first line of the file to execute the code. The current file is valid!

2.set_exception_handler() no longer guarantees that what is received must be an Exception object

在 PHP 7 中,很多致命错误以及可恢复的致命错误,都被转换为异常来处理了。 这些异常继承自 Error 类,此类实现了 Throwable 接口 (所有异常都实现了这个基础接口)。

PHP7进一步方便开发者处理, 让开发者对程序的掌控能力更强. 因为在默认情况下, Error会直接导致程序中断, 而PHP7则提供捕获并且处理的能力, 让程序继续执行下去, 为程序员提供更灵活的选择。

3.新增操作符“<=>”

语法:$c = $a <=> $b

如果$a > $b, $c 的值为1

如果$a == $b, $c 的值为0

如果$a < $b, $c 的值为-1

4.新增操作符“??”

如果变量存在且值不为NULL, 它就会返回自身的值,否则返回它的第二个操作数。

//原写法$username = isset($_GET[&#39;user]) ? $_GET[&#39;user] : &#39;nobody&#39;;//现在$username = $_GET[&#39;user&#39;] ?? &#39;nobody&#39;;
Copy after login

5.define() 定义常量数组

define(&#39;ARR&#39;,[&#39;a&#39;,&#39;b&#39;]);
echo ARR[1];// a
Copy after login

6.AST: Abstract Syntax Tree, 抽象语法树

AST在PHP编译过程作为一个中间件的角色, 替换原来直接从解释器吐出opcode的方式, 让解释器(parser)和编译器(compliler)解耦, 可以减少一些Hack代码, 同时, 让实现更容易理解和可维护.

PHP5 : PHP代码 -> Parser语法解析 -> OPCODE -> 执行
PHP7 : PHP代码 -> Parser语法解析 -> AST -> OPCODE -> 执行

参考: https://wiki.php.net/rfc/abstract_syntax_tree

7.匿名函数

$anonymous_func = function(){return &#39;function&#39;;};echo $anonymous_func(); // 输出function
Copy after login

8.Unicode字符格式支持(echo “\u{9999}”)

9.Unserialize 提供过滤特性

防止非法数据进行代码注入,提供了更安全的反序列化数据。

10.命名空间引用优化

// PHP7以前语法的写法 
use FooLibrary\Bar\Baz\ClassA; 
use FooLibrary\Bar\Baz\ClassB; 
// PHP7新语法写法 
use FooLibrary\Bar\Baz\{ ClassA, ClassB};
Copy after login

PHP7带来的废弃

1.废弃扩展

Ereg 正则表达式
mssql
mysql
sybase_ct

2.废弃的特性

不能使用同名的构造函数
实例方法不能用静态方法的方式调用

3.废弃的函数

方法调用
call_user_method()
call_user_method_array()

应该采用call_user_func() 和 call_user_func_array()

加密相关函数

mcrypt_generic_end()
mcrypt_ecb()
mcrypt_cbc()
mcrypt_cfb()
mcrypt_ofb()

注意: PHP7.1 以后mcrypt_*序列函数都将被移除。推荐使用:openssl 序列函数

杂项

set_magic_quotes_runtime
set_socket_blocking
Split
imagepsbbox()
imagepsencodefont()
imagepsextendfont()
imagepsfreefont()
imagepsloadfont()
imagepsslantfont()
imagepstext()

4.废弃的用法

$HTTP_RAW_POST_DATA 变量被移除, 使用php://input来代

ini文件里面不再支持#开头的注释, 使用”;”

移除了ASP格式的支持和脚本语法的支持: <% 和 < script language=php >

PHP7带来的变更

1.字符串处理机制修改

含有十六进制字符的字符串不再视为数字, 也不再区别对待.

var_dump("0x123" == "291"); // falsevar_dump(is_numeric("0x123")); // falsevar_dump("0xe" + "0x1"); // 0var_dump(substr("f00", "0x1")) // foo
Copy after login

2.整型处理机制修改

Int64支持, 统一不同平台下的整型长度, 字符串和文件上传都支持大于2GB. 64位PHP7字符串长度可以超过2^31次方字节.

// 无效的八进制数字(包含大于7的数字)会报编译错误$i = 0681; // 老版本php会把无效数字忽略。// 位移负的位置会产生异常var_dump(1 >> -1);// 左位移超出位数则返回0var_dump(1 << 64);// 0 // 右位移超出会返回0或者-1var_dump(100 >> 32);// 0 var_dump(-100 >> 32);// -1
Copy after login

3.参数处理机制修改

不支持重复参数命名

function func(a,a,b, c,c,c) {} ;hui报错

func_get_arg()和func_get_args()这两个方法返回参数当前的值, 而不是传入时的值, 当前的值有可能会被修改

所以需要注意,在函数第一行最好就给记录下来,否则后续有修改的话,再读取就不是传进来的初始值了。

function foo($x) {
    $x++;    echo func_get_arg(0);
}
foo(1); //返回2
Copy after login

4.foreach修改

foreach()循环对数组内部指针不再起作用

$arr = [1,2,3];foreach ($arr as &$val) {    echo current($arr);// php7 全返回0}
Copy after login

按照值进行循环的时候, foreach是对该数组的拷贝操作

$arr = [1,2,3];foreach ($arr as $val) {    unset($arr[1]);
}
var_dump($arr);
Copy after login

最新的php7依旧会打印出[1,2,3]。(ps:7.0.0不行)
老的会打印出[1,3]

按照引用进行循环的时候, 对数组的修改会影响循环

$arr = [1];foreach ($arr as $val) {
    var_dump($val);    $arr[1]=2;
}
Copy after login

最新的php7依旧会追加新增元素的循环。(ps:7.0.0不行)

5. list修改

不再按照相反的顺序赋值

//$arr将会是[1,2,3]而不是之前的[3,2,1]list($arr[], $arr[], $arr[]) = [1,2,3];
Copy after login

不再支持字符串拆分功能

// $x = null 并且 $y = null$str = &#39;xy&#39;;
list($x, $y) = $str;
Copy after login

空的list()赋值不再允许

list() = [123];
Copy after login

list()现在也适用于数组对象

list($a, $b) = (object)new ArrayObject([0, 1]);
Copy after login

6.变量处理机制修改

对变量、属性和方法的间接调用现在将严格遵循从左到右的顺序来解析,而不是之前的混杂着几个特殊案例的情况。 下面这张表说明了这个解析顺序的变化。

A quick summary of new features in PHP7

引用赋值时自动创建的数组元素或者对象属性顺序和以前不同了

$arr = [];$arr[&#39;a&#39;] = &$arr[&#39;b&#39;];$arr[&#39;b&#39;] = 1;
// php7: [&#39;a&#39; => 1, &#39;b&#39; => 1]
// php5: [&#39;b&#39; => 1, &#39;a&#39; => 1]
Copy after login

7.杂项

1.debug_zval_dump() 现在打印 “int” 替代 “long”, 打印 “float” 替代 “double”

2.dirname() 增加了可选的第二个参数, depth, 获取当前目录向上 depth 级父目录的名称。

3.getrusage() 现在支持 Windows.mktime() and gmmktime() 函数不再接受 is_dst 参数。

4.preg_replace() 函数不再支持 “\e” (PREG_REPLACE_EVAL). 应当使用 preg_replace_callback() 替代。

5.setlocale() 函数不再接受 category 传入字符串。 应当使用 LC_* 常量。

6.exec(), system() and passthru() 函数对 NULL 增加了保护.

7.shmop_open() now returns a resource instead of an int. This resource can be passed to shmop_size(), shmop_write(), shmop_read(), shmop_close() and shmop_delete().

8. To avoid memory leaks, xml_set_object() now requires manual clearing of $parse at the end of execution.

9.curl_setopt setting item CURLOPT_SAFE_UPLOAD change

TRUE disables the @ prefix for sending files in CURLOPT_POSTFIELDS. This means @ can be safely used in fields. CURLFile can be used as an upload alternative.
Added in PHP 5.5.0, default value is FALSE. PHP 5.6.0 changes the default value to TRUE. . PHP 7 removed this option and you must use the CURLFile interface to upload files.

How to give full play to the performance of PHP7

1. Turn on Opcache

##zend_extension=opcache.so

opcache. enable=1
opcache.enable_cli=1

2. Use GCC 4.8 or above to compile

Only GCC 4.8 or above PHP will open Global Register for opline and execute_data support, this will bring about 5% performance improvement (measured from the QPS perspective of Wordpres)

3. Turn on HugePage (determined based on system memory)

A quick summary of new features in PHP7

4.PGO (Profile Guided Optimization)

After the first successful compilation, use the project code to train PHP, which will generate some profile information. Finally, based on these Information Compile PHP with gcc for the second time and you can get tailor-made PHP7

You need to choose the scenario you want to optimize: the page with the most visits, the most time-consuming, and the heaviest resource consumption.

Reference: http://www.laruence.com/2015 /06/19/3063.html
Reference: http://www.laruence.com/2015/12/04/3086.html

How to write code better to welcome PHP7 ?

  1. Do not use the abandoned methods of php7, extend
  2. Use syntax features that are compatible with both versions [list, foreach, func_get_arg, etc.]

How to upgrade the current project code to be compatible with PHP7?

Gradually eliminate the code that php7 does not support

Detection tool: https:// github.com/sstalle/php7cc

A quick summary of new features in PHP7

The above is the detailed content of A quick summary of new features in PHP7. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!