Assuming I have this trait:
trait MyTrait{
protected static $_statVar = 'defaultStaticVal';
protected $_var = 'defaultVal';
}
And a class that uses it
class MyClass{
use MyTrait;
}
How would I go about changing the default values, like
use MyTrait{
MyTrait::$_statVar = 'nonDefaultStaticVal';
MyTrait->_var = 'nonDefaultVal';
}
I know that the shown syntax is incorrect, and also that currently, it is not allowed to change inherited trait values simply by changin them. What choices/alternatives does that leave me with?
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With