PHP 扩展类和特征启动控制
我创建了一个小助手,可以解决大多数情况,并在类 + 特征引导过程中扩展您的执行优先级。以下示例中使用的数字尊重设置顺序。类似于 Laravel 的启动机制。
一个助手类:
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();
}
}
}
}
你的班:
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;
}
}
你的特质:
trait MyTrait {
// Trait default values
protected $traitVar = 3;
// Called on "bootUsedTraits"
public function bootMyTrait() {
self::$a = 7;
$this->b = 8;
$this->traitVar = 9;
}
}