php8 vs php7
三次求平均值:8.0.0 with jit on7.3.25
1.22349905967713.6357760429382
由此可见性能提升还是明显的。(pis: 但是8如果关掉jit 测试性能还不如7 这块我也很疑惑,正在找原因。。。todo)
jit为啥能让执行性能提升?可以看下上面给的鸟哥的博客,在此就不赘述了。
Attributes (注解)
最近一直在用spring boot开发项目,给我印象最深的就是可以使用各种注释定义类,方法以及变量等,这样在代码书写比较优雅简洁的同时,提高了开发效率。现在php8的注解(Attributes)功能也来了
Attributes其实是依靠反射函数去实现价值的,以往也会用到php的反射函数,不过大多数情况下是用来自动生成API文档的时候才使用的,感觉没有太大的发挥空间。
/**
* @name 测试方法
* @author yangyanlei
*/
function test($params){}
$ref = new ReflectionFunction("test");
$doc = $ref->getDocComment();
print_r($doc);
执行获取信息如下:
/** * @name 测试方法 * @author yangyanlei */
这样简单粗暴的把注释里面的信息获取,然后再用字符串函数进行处理,不够规范也容易出错。
新的写法:
#[name("测试方法")]
#[author("yangyanlei")]
function test($params) {}
$ref = new ReflectionFunction("test");
print_r($ref->getAttributes("name")[0]->getArguments());
输出内容:
Array ( [0] => 测试方法 )
以后也可以这样实现注解及配置
#[Attribute]
class MyAttribute {
public function __construct($name, $value) {
print_r($name);
print_r($value);
}
}
#[MyAttribute("testname", "testvalue")]
function test($argument) {
}
$ref = new ReflectionFunction("test");
$ref->getAttributes("MyAttribute")[0]->newInstance();
程序输出:
testnametestvalue
虽然现在觉得好像用处不大,但是谁又能保证之后php不会出一个类似于spring boot注解的AOP开源框架呢,期待。。联合类型
自7开始,php已经支持类型声明,但是只支持单个类型声明,而联合声明是接收不同类型的值,而不是单个类型,语法指定T1|T2|...。之前不确定类型只能用?代替 ♂️
public function foo(Foo|Bar $input): int|float;
这个特性没什么可说的 不过有几个点需要注意可空联合类型:null类型可以作为联合类型的一部分 T1|T2|null因此可用于创建可为空的联合。
void是一个返回类型,指示函数不返回值。因此,它不能成为联合类型声明的一部分
match表达式
php8新增match表达式的支持,感觉就是switch的语法糖
function switchDemo($input) {
$res = 0;
switch ($input) {
case 1:
$res = 1;
break;
case 2:
$res = 2;
break;
default:
$res = 3;
}
echo $res . "\n";
}
echo switchDemo(1);
echo switchDemo(2);
echo switchDemo(3);
?>
输出:
1 2 3
match写法:
function matchdemo($input) {
echo match ($input) {
1 => 1,
2 => 2,
3 => 3
};
}
echo matchdemo(1);
echo matchdemo(2);
echo matchdemo(3);
?>
输出:
123
并且,类似switch的多个case一个block一样,match的多个条件也可以写在一起,比如:
$result = match($input) {
"true", "on" => 1,
"false", "off" => 0,
"null", "empty", "NaN" => NULL,
};
结语
以上,本文会随时更新补充,希望phper越来越好,希望php越来越好。