php 对象 随版本变化
PHP 5.6
class BlogData{ /** @var string */ private $title; /** @var State */ private $state; /** @var \DateTimeImmutable|null */ private $publishedAt; /** * @param string $title * @param State $state * @param \DateTimeImmutable|null $publishedAt */ public function __construct($title,$state,$publishedAt = null) { $this->title = $title; $this->state = $state; $this->publishedAt = $publishedAt; } /** * @return string */ public function getTitle(){ return $this->title; } /** * @return State */ public function getState() { return $this->state; } /** * @return \DateTimeImmutable|null */ public function getPublishedAt() { return $this->publishedAt; } }
php7 引入 标量类型和返回类型
class BlogData{ /** @var string */ private $title; /** @var State */ private $state; /** @var \DateTimeImmutable|null */ private $publishedAt; /** * @param \DateTimeImmutable|null $publishedAt */ public function __construct(string $title,State $state,$publishedAt = null) { $this->title = $title; $this->state = $state; $this->publishedAt = $publishedAt; } public function getTitle(): string { return $this->title; } public function getState(): State { return $this->state; } /** * @return \DateTimeImmutable|null */ public function getPublishedAt() { return $this->publishedAt; } }
PHP 7.1 终于出现了可以为空的类型
class BlogData{ /** @var string */ private $title; /** @var State */ private $state; /** @var \DateTimeImmutable|null */ private $publishedAt; public function __construct( string $title, State $state, ?DateTimeImmutable $publishedAt = null) { $this->title = $title; $this->state = $state; $this->publishedAt = $publishedAt; } public function getTitle(): string { return $this->title; } public function getState(): State { return $this->state; } public function getPublishedAt(): ?DateTimeImmutable { return $this->publishedAt; } }
PHP 7.4 类型化属性
class BlogData{ private string $title; private State $state; private ?DateTimeImmutable $publishedAt; public function __construct( string $title, State $state, ?DateTimeImmutable $publishedAt = null) { $this->title = $title; $this->state = $state; $this->publishedAt = $publishedAt; } public function getTitle(): string { return $this->title; } public function getState(): State { return $this->state; } public function getPublishedAt(): ?DateTimeImmutable { return $this->publishedAt; } }
PHP 8.0 增加了提升属性
class BlogData{ public function __construct( private string $title, private State $state, private ?DateTimeImmutable $publishedAt = null, ){} public function getTitle(): string { return $this->title; } public function getState(): State { return $this->state; } public function getPublishedAt(): ?DateTimeImmutable { return $this->publishedAt; } }
php8.1 只读属性
class BlogData{ public function __construct( public readonly string $title, public readonly State $state, public readonly ?DateTimeImmutable $publishedAt = null,) {} }
评论区
请登陆 后评论!