PHP extend class & trait booting control
I created a small helper that solves most situations and expand your execution priorities on the class + trait booting process. The numbers used on the following example respect order of setting. Similar to the Laravel booting mechanism.
A helper class:
class TraitHelper
{
// The helper will call the boot function on every used trait.
static public function bootUsedTraits($obj)
{
$usedTraits = class_uses($obj);
foreach ($usedTraits as $traitClass) {
$path = explode('\\', $traitClass);
$traitBootMethod = array_pop($path);
$traitBootMethod = 'boot'.$traitBootMethod;
if (method_exists($obj, $traitBootMethod)) {
$obj->$traitBootMethod();
}
}
}
}
Your class:
class MyClass{
use MyTrait;
// Class default values
static protected $a = 1;
protected $b = 2;
function __construct()
{
// Class setting values before trait
self::$a = 4;
$this->b = 5;
$this->traitVar = 6;
// Trait setting values
\TraitHelper::bootUsedTraits($this);
// Class setting values after trait
self::$a = 10;
$this->b = 11;
$this->traitVar = 12;
}
}
Your trait:
trait MyTrait {
// Trait default values
protected $traitVar = 3;
// Called on "bootUsedTraits"
public function bootMyTrait() {
self::$a = 7;
$this->b = 8;
$this->traitVar = 9;
}
}