PHP - Custom Type Traits


To inherit code from multiple places, you have traits.

Traits reuses code from multiple sources at the same time.

Traits cannot be instantiated.

They are just containers of functionality that can be used from other classes.

To define a trait, use the keyword trait instead of class.

    trait Unique { 
        private static $lastId = 0; 
        protected $id; 

        public function setId(int $id) { 
            if (empty($id)) { 
                $this->id = ++self::$lastId; 
            } else { 
                $this->id = $id; 
                if ($id > self::$lastId) { 
                    self::$lastId = $id; 

        public static function getLastId(): int { 
            return self::$lastId; 
        public function getId(): int { 
            return $this->id; 

Here, we include all the code related to IDs.

That includes the properties, the getters and setters, and the code inside the constructor.

To include traits to a class, we use the keyword use inside the class.

    class Person { 
        use Unique; 
        protected $firstname; 
        protected $surname; 
        protected $email; 

        public function __construct( 
            int $id, 
            string $firstname, 
            string $surname, 
            string $email 
        ) { 
            $this->firstname = $firstname; 
            $this->surname = $surname; 
            $this->email = $email; 

        public function getFirstname(): string { 
            return $this->firstname; 
        public function getSurname(): string { 
            return $this->surname; 
        public function getEmail(): string { 
            return $this->email; 
        public function setEmail(string $email) { 
            $this->email = $email; 

We add the use Unique; statement to let the class know that it is using the trait.

We use the method from traits as if it was inside the class.