Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
<?php trait Timestampable { private ?string $createdAt = null; private ?string $updatedAt = null; public function setCreatedAt(): void { $this->createdAt = date('Y-m-d H:i:s'); } public function setUpdatedAt(): void { $this->updatedAt = date('Y-m-d H:i:s'); } public function getCreatedAt(): ?string { return $this->createdAt; } public function getUpdatedAt(): ?string { return $this->updatedAt; } } trait SoftDeletable { private ?string $deletedAt = null; public function softDelete(): void { $this->deletedAt = date('Y-m-d H:i:s'); } public function restore(): void { $this->deletedAt = null; } public function isDeleted(): bool { return $this->deletedAt !== null; } } class Post { use Timestampable, SoftDeletable; // use multiple traits public function __construct(public string $title) { $this->setCreatedAt(); } public function update(string $title): void { $this->title = $title; $this->setUpdatedAt(); } } $post = new Post('Hello World'); echo $post->getCreatedAt(); // 2024-07-15 14:00:00 $post->update('Hello PHP'); echo $post->getUpdatedAt(); // 2024-07-15 14:00:01 $post->softDelete(); echo $post->isDeleted() ? 'deleted' : 'active'; // deleted $post->restore(); echo $post->isDeleted() ? 'deleted' : 'active'; // active
Result
Open