Interfaces and Traits
Trait State
A trait can provide methods that update state stored on the object.
Trait State
trait_state.php
<?php
trait CountsItems
{
private int $count = 0;
public function add(int $items): int
{
$this->count = $this->count + $items;
return $this->count;
}
}
class Basket
{
use CountsItems;
}
$items = ;
$basket = new Basket();
$total = $basket->add($items);
echo "items=" . $items . "\n";
echo "total=" . $total . "\n";
<?php
trait CountsItems
{
private int $count = 0;
public function add(int $items): int
{
$this->count = $this->count + $items;
return $this->count;
}
}
class Basket
{
use CountsItems;
}
$items = ;
$basket = new Basket();
$total = $basket->add($items);
echo "items=" . $items . "\n";
echo "total=" . $total . "\n";
<?php
trait CountsItems
{
private int $count = 0;
public function add(int $items): int
{
$this->count = $this->count + $items;
return $this->count;
}
}
class Basket
{
use CountsItems;
}
$items = ;
$basket = new Basket();
$total = $basket->add($items);
echo "items=" . $items . "\n";
echo "total=" . $total . "\n";
shared state helper
Trait methods are useful when several classes need the same small state update.