首页 » SEO优化 » php结构类技巧_PHP8新特点系列构造器属性提升运用及留心事项

php结构类技巧_PHP8新特点系列构造器属性提升运用及留心事项

访客 2024-10-28 0

扫一扫用手机浏览

文章目录 [+]

class Point { public int $x; private string $y; public function __construct(int $x = 0, string $y='') { $this->x = $x; $this->y = $y; }}

在PHP8中则可以简化为直接在布局函数方法里面定义类的属性

class Point { public function __construct(public int $x = 0, private string $y = '') { // 你可以在布局器中直接输出类的x和y属性的值(也便是传入的x和y变量的值) var_dump($this->x); var_dump($this->y); }}

不过须要把稳的是布局器属性只能在布局器方法中定义(彷佛是废话),而且必须添加public/protected/private,如果不添加的话是不会作为类属性定义的,除非你在父类中已经定义告终构器属性,比如:

php结构类技巧_PHP8新特点系列构造器属性提升运用及留心事项

class Test { public function __construct( public int $x = 0 ) {}}class Child extends Test { public function __construct( $x, public int $y = 0, public int $z = 0, ) { parent::__construct($x); }}

在实际利用过程中,还有些细节须要把稳。

php结构类技巧_PHP8新特点系列构造器属性提升运用及留心事项
(图片来自网络侵删)
抽象类或接口的布局器方法不能利用布局器属性定义

abstract class Test { // 缺点 abstract public function __construct(private $x);} interface Test { // 缺点 public function __construct(private $x);}

但Traits中是许可利用的

trait MyTrait{ public function __construct( public string $a, ) {}}工具类型的布局器属性不能利用null作为默认值

如果你的布局器属性的类型是一个工具,那么不可以利用null作为参数默认值

class Test { // 缺点 public function __construct(public Type $prop = null) {}}

但可以利用

class Test { // 精确 public function __construct(public ?Type $prop = null) {}}不支持callable类型的布局器属性定义

class Test { // 缺点 public function __construct(public callable $callback) {}}布局器属性不能利用var定义

class Test { // 缺点 public function __construct(var $prop) {}}布局器属性定义也不能利用可变参数

class Test { // Error: Variadic parameter. public function __construct(public string ...$strings) {}}布局器属性和类属性不能重复定义

比如

class Test { public string $prop; public int $explicitProp; // Error: Redeclaration of property. public function __construct(public string $prop) {}}

但你可以利用布局器属性定义额外的尚未定义过的类属性

class Test { public string $prop; public int $explicitProp; // Correct public function __construct(public int $promotedProp, int $arg) { $this->explicitProp = $arg; }}只能利用大略默认值

比如,你不可以在参数的默认值中利用函数或者实例化工具。

public function __construct( public string $name = 'Brent', // 缺点 public DateTime $date = new DateTime(),) {}

更多的用法可以自行研究。

相关文章