Home>Article>Backend Development> Thoroughly explain PHP7 and comprehensively introduce the new features of PHP7

Thoroughly explain PHP7 and comprehensively introduce the new features of PHP7

PHP中文网
PHP中文网 forward
2019-05-21 16:00:29 6341browse

Preface

This article is a summary of a lecture + follow-up research. (Study recommendation:PHP video tutorial)

Speaking of following the fashion back then, php7 was immediately installed on the computer as soon as it came out. php5 and php7 coexisted, and it was also very time-consuming to write it immediately. I tested the loop script and found that php7 is indeed much more powerful. I also paid attention to some new features and some discarded usages.

Since php upgrade is a top priority, the company only plans to upgrade in the near future, so before, I could only enjoy the pleasure brought by php7 in private. The friend in charge of the upgrade made a sharing, which is quite comprehensive. Mark here Take it as a note. (Topic recommendation:PHP7 topic)

Thoroughly explain PHP7 and comprehensively introduce the new features of PHP7

##Main research questions:

1. The benefits brought by PHP7

2. The new things brought by PHP7

3. The obsolescence brought by PHP7

4. The changes brought by PHP7

5. How to give full play to the performance of PHP7

6. How to write better code to meet PHP7?

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

Benefits of PHP7

Yes, the performance has been greatly improved, which can save machines and save money.

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

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

In PHP 7, many fatal errors and recoverable fatal errors have been Converted to exception to handle. These exceptions inherit from the Error class, which implements the Throwable interface (all exceptions implement this base interface).

PHP7 further facilitates developers' processing and allows developers to have greater control over the program. Because by default, Error will directly cause the program to interrupt, while PHP7 provides the ability to capture and process it, allowing the program to continue. The implementation continues to provide programmers with more flexible options.

3. New operator ""

Syntax: $c = $a $b

If $a > $b, the value of $c is 1

If $a == $b, the value of $c is 0

If $a

4. New operator "??"

If the variable exists and the value is not NULL, it will return its own value. Otherwise its second operand is returned.

//原写法 $username = isset($_GET['user]) ? $_GET['user] : 'nobody'; //现在 $username = $_GET['user'] ?? 'nobody';

5. define() defines a constant array

define('ARR',['a','b']); echo ARR[1];// a

6. AST: Abstract Syntax Tree, Abstract Syntax Tree

AST plays the role of a middleware in the PHP compilation process, replacing the original method of spitting out opcode directly from the interpreter, decoupling the interpreter (parser) and the compiler (compliler), which can reduce some Hack codes and make the implementation more efficient. Easy to understand and maintainable.

PHP5: PHP code-> Parser syntax analysis-> OPCODE-> Execution

PHP7: PHP code-> Parser syntax analysis-> AST -> OPCODE -> Execution

Reference: https://wiki.php.net/rfc/abstract_syntax_tree

7. Anonymous function

$anonymous_func = function(){return 'function';}; echo $anonymous_func(); // 输出function

8. Unicode character format support (echo “\u{9999}”)

9. Unserialize provides filtering features

to prevent illegal Code injection of data provides safer deserialization of data.

10. Namespace reference optimization

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

Abandoned by PHP7

1. Deprecated extension

Ereg regular expression

mssql

mysql

sybase_ct

2. Deprecated features

Constructors with the same name cannot be used

Instance methods cannot be called as static methods

3. Deprecated functions

Method call


call_user_method() call_user_method_array()

Should use call_user_func() and call_user_func_array()

加密相关函数 mcrypt_generic_end() mcrypt_ecb() mcrypt_cbc() mcrypt_cfb() mcrypt_ofb()

Note: mcrypt_* sequence functions will be removed after PHP7.1. Recommended use: openssl sequence function

Miscellaneous


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

4. Deprecated usage

$HTTP_RAW_POST_DATA variable has been removed, use php: //input to represent

The ini file no longer supports comments starting with #, use ";"

Removed ASP format support and script syntax support:

PHP7带来的变更

1.字符串处理机制修改

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

var_dump("0x123" == "291"); // false var_dump(is_numeric("0x123")); // false var_dump("0xe" + "0x1"); // 0 var_dump(substr("f00", "0x1")) // foo

2.整型处理机制修改

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

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

3.参数处理机制修改

不支持重复参数命名

function func(a,b, c,c) {} ;hui报错 func_get_arg()和func_get_args()这两个方法返回参数当前的值, 而不是传入时的值, 当前的值有可能会被修改


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

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

4.foreach修改

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

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

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

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

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

老的会打印出[1,3]

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

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

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

5. list修改

不再按照相反的顺序赋值

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

不再支持字符串拆分功能

// $x = null 并且 $y = null $str = 'xy'; list($x, $y) = $str;

空的list()赋值不再允许

list() = [123];

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

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

6.变量处理机制修改

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

Thoroughly explain PHP7 and comprehensively introduce the new features of PHP7引用赋值时自动创建的数组元素或者对象属性顺序和以前不同了

$arr = []; $arr['a'] = &$arr['b']; $arr['b'] = 1; // php7: ['a' => 1, 'b' => 1] // php5: ['b' => 1, 'a' => 1]

7.杂项

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

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

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

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

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

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

07.shmop_open() 现在返回一个资源而非一个int, 这个资源可以传给shmop_size(), shmop_write(), shmop_read(), shmop_close() 和 shmop_delete().

08.为了避免内存泄露,xml_set_object() 现在在执行结束时需要手动清除 $parse。

09.curl_setopt 设置项CURLOPT_SAFE_UPLOAD变更

TRUE 禁用 @ 前缀在 CURLOPT_POSTFIELDS 中发送文件。 意味着 @ 可以在字段中安全得使用了。 可使用 CURLFile作为上传的代替。

PHP 5.5.0 中添加,默认值 FALSE。 PHP 5.6.0 改默认值为 TRUE。. PHP 7 删除了此选项, 必须使用 CURLFile interface 来上传文件。

如何充分发挥PHP7的性能

1.开启Opcache

zend_extension=opcache.so

opcache.enable=1

opcache.enable_cli=1

2.使用GCC 4.8以上进行编译

只有GCC 4.8以上PHP才会开启Global Register for opline and execute_data支持, 这个会带来5%左右的性能提升(Wordpres的QPS角度衡量)

3.开启HugePage (根据系统内存决定)

Thoroughly explain PHP7 and comprehensively introduce the new features of PHP7

4.PGO (Profile Guided Optimization)

第一次编译成功后,用项目代码去训练PHP,会产生一些profile信息,最后根据这些信息第二次gcc编译PHP就可以得到量身定做的PHP7

需要选择在你要优化的场景中: 访问量最大的, 耗时最多的, 资源消耗最重的一个页面.

参考: http://www.laruence.com/2015/06/19/3063.html

参考: http://www.laruence.com/2015/12/04/3086.html

如何更好的写代码来迎接PHP7?

1. 不使用php7废弃的方法,扩展

2. 使用2个版本都兼容的语法特性【 list ,foreach, func_get_arg 等】

如何升级当前项目代码来兼容PHP7?

逐步剔除php7不支持的代码

检测工具:https://github.com/sstalle/php7cc

Thoroughly explain PHP7 and comprehensively introduce the new features of PHP7

更多资料

The above is the detailed content of Thoroughly explain PHP7 and comprehensively introduce the new features of PHP7. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete