Web Analytics

PHP Traits

Intermediate~25 min read

Traits enable horizontal code reuse - share methods across unrelated classes without inheritance. Perfect for adding common functionality!

Output
Click Run to execute your code

Defining a Trait

<?php
trait Timestampable {
    public function setTimestamps() {
        $this->createdAt = date('Y-m-d H:i:s');
    }
}
?>

Using a Trait

<?php
class Post {
    use Timestampable;
    
    public $title;
}

$post = new Post();
$post->setTimestamps();  // From trait!
?>

Multiple Traits

<?php
class Post {
    use Timestampable, Loggable, Cacheable;
}
?>

Summary

  • trait: Define reusable methods
  • use: Include trait in class
  • Multiple: Use many traits
  • Horizontal: Reuse without inheritance

What's Next?

Next, learn about Static Members - class-level properties and methods!