php8编程语言版本新特性

2021-10-02  本文已影响0人  知码客

1、PHP8如约而至

访问 PHP官方,我们已经可以看到php8稳定版已经可以下载使用了,这对PHP来说是一个重大版本。有别于PHP7,万众瞩目的Just In Time Compilation(即时编译)功能成为了大家期待的重点。
php8下载地址:官网php.net
php8新特性介绍:

2、PHP8新特性

1.命名参数
php8支持命名参数,这样靠前的有默认的参数,就不用必须明确写出,如下php8跳过第二和第三个默认参数,直接指定第四个参数。开发者可以按自己的意愿更改参数顺序,这样的好处是,摆脱了php函数有些不经常用的参数靠前,代码中又必须明确写出才能给后面的参数赋值的困扰。
简单例子如下:详情参考

//php7
htmlspecialchars($string, ENT_COMPAT | ENT_HTML401, 'UTF-8', false);

//php8
htmlspecialchars($string, double_encode: false);

2.注解语法
通过重复使用现有标记T_SL和T_SR,注解是用“ <<”和“ >>”括起来的特殊格式的文本。详情参考

注解可以用该语言应用于许多事物:
函数(包括闭包和短闭包)
类(包括匿名类),接口,特征
类常量
类属性
类方法
功能/方法参数
namespace MyAttributes {

<<PhpAttribute>>
class SingleArgument {
    public $argumentValue;

    public function __construct($argumentValue) {
         $this->argumentValue = $argumentValue;
    }
}

}

namespace {
<<SingleArgument("Hello World")>>
class Foo {
}

$reflectionClass = new ReflectionClass(Foo::class);
$attributes = $reflectionClass->getAttributes();

var_dump($attributes[0]->getName());
var_dump($attributes[0]->getArguments());
var_dump($attributes[0]->newInstance());

}

/**
string(28) "MyAttributesSingleArgument"
array(1) {
[0]=>
string(11) "Hello World"
}
object(MyAttributesSingleArgument)#1 (1) {
["argumentValue"]=>
string(11) "Hello World"
}
**/

3.构造函数参数的改进
//php7
class Point {
public float x; public floaty;
public float $z;

public function __construct(
float x = 0.0, floaty = 0.0,
float z = 0.0, ) {this->x = x;this->y = y;this->z = $z;
}
}

//php8
class Point {
public function __construct(
public float x = 0.0, public floaty = 0.0,
public float $z = 0.0,
) {}
}

4.联合类型

当给函数传参,参数可能有多重类型,传统PHP7下并不支持校验,PHP8可以完美实现校验。
//php7
class Number {
/** @var int|float */
private $number;

/**

new Number('NaN'); // Ok

//php8
class Number {
public function __construct(
private int|float $number
) {}
}

new Number('NaN'); // TypeError

5.匹配表达式

php8拥有更精简的新语法,这个赞成的成员非常多,反对的很少,可见大家对switch语法意见颇大。
//php7switch (8.0) {
case '8.0':
result = "Oh no!"; break; case 8.0:result = "This is what I expected";
break;}echo $result;
//php8
echo match (8.0) {
'8.0' => "Oh no!",
8.0 => "This is what I expected",};

6.空安全运算符
//php7
country = null;if (session !== null) {
user =session->user;

if (user !== null) {address = $user->getAddress();

if ($address !== null) {
  $country = $address->country;
}

}}
//php8
country =session?->user?->getAddress()?->country;

7.字符串和数字比较

在php8中,数字和字符串比较时,会将数字转成字符串,正好和之前相反。
//php7
0 == 'foobar' // true
//php8
0 == 'foobar' // false

8.函数内部一致性校验错误
//php7
strlen([]);
// Warning: strlen() expects parameter 1 to be string, array givenarray_chunk([], -1);
// Warning: array_chunk(): Size parameter expected to be greater than 0
//php8
strlen([]);
// TypeError: strlen(): Argument #1 (str) must be of type string; // ValueError: array_chunk(): Argument #2 (length) must be greater than 0

上一篇 下一篇

猜你喜欢

热点阅读