Home  >  Article  >  Backend Development  >  Play with the new features of PHP7 in one minute

Play with the new features of PHP7 in one minute

慕斯
慕斯forward
2021-06-23 12:00:061584browse

Speaking of following the fashion back then, 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. Then I also paid attention to some new features and some discarded usages. Regarding these new features, we still need to learn about them together

Preface

Main research questions:
1.Benefits brought by PHP7
2. New things brought by PHP7
3. Obsolescence 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.
Play with the new features of PHP7 in one minute

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

In PHP 7, there are many fatal errors and recoverable Fatal errors are converted into exceptions and handled. These exceptions inherit from the Error class, which implements the Throwable interface (all exceptions implement this base interface).

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

3.新增操作符“”

语法:$c = $a $b

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

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

如果$a

4.新增操作符“??”

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

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

5.define() 定义常量数组

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

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 'function';};echo $anonymous_func(); // 输出function

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

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格式的支持和脚本语法的支持:

PHP7带来的变更

1.字符串处理机制修改

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

var_dump("0x123" == "291"); // falsevar_dump(is_numeric("0x123")); // falsevar_dump("0xe" + "0x1"); // 0var_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,a,b, c,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 = &#39;xy&#39;;
list($x, $y) = $str;

空的list()赋值不再允许

list() = [123];

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

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

6.变量处理机制修改

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

Play with the new features of PHP7 in one minute

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

$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]

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() 现在返回一个资源而非一个int, 这个资源可以传给shmop_size(), shmop_write(), shmop_read(), shmop_close() 和 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)

Play with the new features of PHP7 in one minute

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

How to better write code to welcome PHP7?

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

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

Gradually eliminate the code that is not supported by php7

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

Play with the new features of PHP7 in one minute

##Recommended learning:

php Video tutorial

The above is the detailed content of Play with the new features of PHP7 in one minute. 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