Interfaces and Traits
Trait Method
A trait can contribute a reusable method to a class.
Trait Method
trait_method.php
<?php
trait HasLabel
{
public function label(): string
{
return "tag:" . $this->name;
}
}
class Tag
{
use HasLabel;
public function __construct(public string $name)
{
}
}
$name = ;
$tag = new Tag($name);
$label = $tag->label();
echo "name=" . $name . "\n";
echo "label=" . $label . "\n";
<?php
trait HasLabel
{
public function label(): string
{
return "tag:" . $this->name;
}
}
class Tag
{
use HasLabel;
public function __construct(public string $name)
{
}
}
$name = ;
$tag = new Tag($name);
$label = $tag->label();
echo "name=" . $name . "\n";
echo "label=" . $label . "\n";
<?php
trait HasLabel
{
public function label(): string
{
return "tag:" . $this->name;
}
}
class Tag
{
use HasLabel;
public function __construct(public string $name)
{
}
}
$name = ;
$tag = new Tag($name);
$label = $tag->label();
echo "name=" . $name . "\n";
echo "label=" . $label . "\n";
method reuse
The class uses the trait method as if the method were written in the class.