php8新特性,在class类定义方面,有什么新特性?
发布于 作者:苏南大叔 来源:程序如此灵动~
本文继续探讨php8
在类定义方面的新特性,当然本文的写法还是不能被vscode
中的代码查错工具所通过,这个就静待后续更新吧。本文的主要内容:php8
对于class
类的特性更新,主要在于类属性的定义及初始化方面。
苏南大叔的“程序如此灵动”博客,记录苏南大叔的代码编程经验文章。本文测试环境:win10
,nginx@1.15.11
,php@8.2.10-nts
。
传统类定义
php
类定义方式也有很多次大的变动了。目前,被支持的类定义方式,类似如下代码:
class Person{
public string $name;
private string $blog;
public function __construct(string $name,string $blog){
$this->name = $name;
$this->blog = $blog;
}
public function getBlog(){
return $this->blog;
}
}
$p = new Person("苏南大叔","newsn.com.cn");
echo $p->name;
echo $p->getBlog();
新的php8
类定义方式
传统的类定义方式,在php@8
里面还是能识别运行的,这里就是新增了新的简写的方式。
class Person2{
public function __construct(public string $name,private string $blog){
}
public function getBlog(){
return $this->blog;
}
}
$p2 = new Person2("sunan大叔","newsn.net");
echo $p2->name;
echo $p2->getBlog();
关键代码字样是:
public function __construct(public string $s,private string $n){}
最大的变化是:
- 类属性不用单独定义了,直接放在了
__construct()
构造函数里面。 - 除了类属性的类型之外,公有私有的定义,也可以直接放在
__construct()
构造函数定义里面。 - 在构造函数里面,不用写
$this->属性名=$属性值
这种初始化代码了。
相关文章
结束语
更多php
经验文章,请点击苏南大叔的文章列表:


