PHP RFC: Typed Properties 2.0 通过,PHP 7.4 新特性 类属性的类型声明
随着标量类型和返回类型的引入,PHP 7 大大增强了 PHP 类型系统的功能。 但是,目前无法为类属性声明类型,从而迫使开发人员使用 getter 和 setter 方法来强制执行类型契约。 这要求了不必要的样板,使得使用不那么符合人体工程学的方式,并且对性能有不好影响。 此 RFC 通过引入对类属性类型声明的支持来解决该问题。
此前,
class User {
/** @var int $id */
private $id;
/** @var string $name */
private $name;
public function __construct(int $id, string $name) {
$this->id = $id;
$this->name = $name;
}
public function getId(): int {
return $this->id;
}
public function setId(int $id): void {
$this->id = $id;
}
public function getName(): string {
return $this->name;
}
public function setName(string $name): void {
$this->name = $name;
}
}
现在,
class User {
public int $id;
public string $name;
public function __construct(int $id, string $name) {
$this->id = $id;
$this->name = $name;
}
}