php8新特性
<?php
header("Content-type:text/html;charset=utf-8");
ini_set('error_reporting', E_ALL);
ini_set("display_errors", "On");//打开错误提示
ini_set('memory_limit', '-1');
set_time_limit(0);
//函数只接受整数或浮点数作为参数
function unionType(int|float $a, array|string $b = null) {
var_dump($a);
var_dump($b);
}
//Union Types(联合类型)
unionType(1);
unionType(1.52);
//unionType("abcd"); //这条会报Fatal error
echo "\n";
//Named Arguments(命名参数)
unionType(a:1, b:"aaa");
echo "\n";
//Match 表达式
echo match(0){
'a' => 'aaa',
'b' => 'bbb',
'c' => 'ccc',
default => '000',
};
echo match("c"){
'a' => 'aaa',
'b' => 'bbb',
'c' => 'ccc',
default => '000',
};
echo "\n";
echo "\n";
//Nullsafe 运算符(Nullsafe operator)
class A{
public $a = null;
public $b = null;
function seta(string $a){
$this->a = $a;
return $this;
}
function geta(){
echo $this->a;
return $this;
}
function setb(string $b){
$this->b = $b;
return $this;
}
function getb(){
echo $this->b;
return $this;
}
}
(new A())?->seta("123")?->geta();
echo (new A())?->setb("456")?->b;
echo "\n";
echo "\n";
//构造器属性提升
class Point {
public function __construct(
public float $x = 0.0,
public float $y = 0.0,
public float $z = 0.0,
) {}
}
echo (new Point(6.9, 5.8, 4.7))->x;
echo "\n";
echo "\n";
//字符串与数字的比较更符合逻辑
var_dump(0 == 'foobar'); // false
echo "\n";
echo "\n";
//注解(attributes)
class PostsController{
#[Route("/api/posts/{id}", methods: ["GET"])]
public function get($id) {
/* ... */
}
}
//PHP 8 还有很多其他改动,在这里有详细的说明:https://www.php.net/releases/8.0/zh.php
//其中新增了 3 个函数实用的函数:str_contains()、str_starts_with() 和 str_ends_with()。
var_dump(str_contains("abc", "b"));
var_dump(str_starts_with("abc", "a"));
var_dump(str_ends_with("abc", "c"));
//内部函数类型错误的一致性
//strlen([]); // TypeError: strlen(): Argument #1 ($str) must be of type string, array given
//array_chunk([], -1); // ValueError: array_chunk(): Argument #2 ($length) must be greater than 0
//即时编译
//PHP 8 引入了两个即时编译引擎。 Tracing JIT 在两个中更有潜力,它在综合基准测试中显示了三倍的性能, 并在某些长时间运行的程序中显示了 1.5-2 倍的性能改进。
//典型的应用性能则和 PHP 7.4 不相上下。
/*
类型系统与错误处理的改进
算术/位运算符更严格的类型检测 RFC
Abstract trait 方法的验证 RFC
确保魔术方法签名正确 RFC
PHP 引擎 warning 警告的重新分类 RFC
不兼容的方法签名导致 Fatal 错误 RFC
操作符 @ 不再抑制 fatal 错误。
私有方法继承 RFC
Mixed 类型 RFC
Static 返回类型 RFC
内部函数的类型 Email thread
扩展 Curl、 Gd、 Sockets、 OpenSSL、 XMLWriter、 XML 以 Opaque 对象替换 resource。
*/
/*
其他语法调整和改进
允许参数列表中的末尾逗号 RFC、 闭包 use 列表中的末尾逗号 RFC
无变量捕获的 catch RFC
变量语法的调整 RFC
Namespace 名称作为单个 token RFC
现在 throw 是一个表达式 RFC
允许对象的 ::class RFC
新的类、接口、函数
Weak Map 类
Stringable 接口
str_contains()、 str_starts_with()、 str_ends_with()
fdiv()
get_debug_type()
get_resource_id()
token_get_all() 对象实现
New DOM Traversal and Manipulation APIs
*/
输出:
int(1) NULL float(1.52) NULL int(1) string(3) "aaa" 000ccc 123456 6.9 bool(false) bool(true) bool(true) bool(true)
本文来自博客园,作者:河北大学-徐小波,转载请注明原文链接:https://www.cnblogs.com/xuxiaobo/p/18622443

浙公网安备 33010602011771号