Interfaces and Traits
Trait Method
A trait can contribute a reusable method to a class.
method reuse
The class uses the trait method as if the method were written in the class.
Trait Method
trait_method.php
Replay: real traced execution (multi-file project)
<?php
trait HasLabel
{
public function label(): string
{
return "tag:" . $this->name;
}
}
class Tag
{
use HasLabel;
public function __construct(public string $name)
{
}
}
$name = "beta";
$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 = "alpha";
$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 = "stable";
$tag = new Tag($name);
$label = $tag->label();
echo "name=" . $name . "\n";
echo "label=" . $label . "\n";
$name ← beta
19$name→ beta = "beta"; //@name="alpha", "stable"20$tag = new Tag($namebeta);21$label = $tag->label();public function __construct(public string $name)
14public function __construct(public string $namebeta)15{16}$tag ← Tag
19$name = "beta"; //@name="alpha", "stable"20$tag→ Tag = new Tag($namebeta);21$label = $tagTag->label();public function label(): string
3{4 public function label(): string5 {6 return "tag:" . $this->namebeta;7 }$label ← tag:beta
20$tag = new Tag($name);21$label→ tag:beta = $tagTag->label();2223echo "name=" . $namebeta . "\n";24echo "label=" . $labeltag:beta . "\n";outputname=beta label=tag:beta
$name ← alpha
19$name→ alpha = "alpha";20$tag = new Tag($namealpha);21$label = $tag->label();public function __construct(public string $name)
14public function __construct(public string $namealpha)15{16}$tag ← Tag
19$name = "alpha";20$tag→ Tag = new Tag($namealpha);21$label = $tagTag->label();public function label(): string
3{4 public function label(): string5 {6 return "tag:" . $this->namealpha;7 }$label ← tag:alpha
20$tag = new Tag($name);21$label→ tag:alpha = $tagTag->label();2223echo "name=" . $namealpha . "\n";24echo "label=" . $labeltag:alpha . "\n";outputname=alpha label=tag:alpha
$name ← stable
19$name→ stable = "stable";20$tag = new Tag($namestable);21$label = $tag->label();public function __construct(public string $name)
14public function __construct(public string $namestable)15{16}$tag ← Tag
19$name = "stable";20$tag→ Tag = new Tag($namestable);21$label = $tagTag->label();public function label(): string
3{4 public function label(): string5 {6 return "tag:" . $this->namestable;7 }$label ← tag:stable
20$tag = new Tag($name);21$label→ tag:stable = $tagTag->label();2223echo "name=" . $namestable . "\n";24echo "label=" . $labeltag:stable . "\n";outputname=stable label=tag:stable