Traits in OOP in PHP
As you already know, in PHP, you cannot inherit from multiple classes at once, only from one. We have previously covered a solution to this problem: instead of inheritance, use objects of some classes inside others.
PHP has another way. It consists of using traits. A trait represents a set of properties and methods that can be included in another class. In this case, the properties and methods of the trait will be perceived by the class as its own.
The syntax of a trait is the same as that of a class,
except that the trait name needs
to be declared using the keyword
trait
.
You cannot create an instance of a trait - traits
are intended only for connection to other
classes. The connection itself is carried out
using the command use
, after which
the name of the trait to be connected is specified, separated by a space.
This command is written at the beginning of the class.
Let's look at the application of traits with a practical
example. Suppose we are given this trait
Helper
, containing private properties
name
and age
, as well as their getters:
<?php
trait Helper
{
private $name;
private $age;
public function getName()
{
return $this->name;
}
public function getAge()
{
return $this->age;
}
}
?>
Suppose we also have this class User
,
in whose constructor the properties
name
and age
are set:
<?php
class User
{
public function __construct($name, $age)
{
$this->name = $name;
$this->age = $age;
}
}
?>
Let's now add getters for the properties
of our User
class. But we won't
write them in the class itself, we'll just connect
the Helper
trait, which already has these methods
implemented:
<?php
class User
{
use Helper; // connect the trait
public function __construct($name, $age)
{
$this->name = $name;
$this->age = $age;
}
}
?>
After connecting the trait, the methods and properties of this trait will appear in our class. We will access them as if they were methods and properties of the class itself:
<?php
$user = new User('john', 30);
echo $user->getName(); // will output 'john'
echo $user->getAge(); // will output 30
?>
Implement the City
class with properties
name
, age
, population
and getters for them. Let our class
use the trait Helper
we have already created to shorten its code.