$property在trait中返回绑定到trait而不是类的数据


static::$property in trait returns data bound to the trait instead of class

我想知道static关键字在trait中返回什么?它似乎被绑定到trait上,而不是使用它的类上。例如:

trait Example
{
    public static $returned;
    public static function method()
    {
        if (!eval(''''.get_called_class().'::$returned;')) {
            static::$returned = static::doSomething();
        }   
        return static::$returned;
    }
    public static function doSomething()
    {
        return array_merge(static::$rules, ['did', 'something']);
    }
}
class Test {}
class Test1 extends Test
{
    use Example;
    protected static $rules = ['test1', 'rules'];
}
class Test2 extends Test
{
    use Example;
    protected static $rules = ['test2', 'rules'];
}
// usage
Test1::method();
// returns expected results:
// ['test1', 'rules', 'did', 'something'];
Test2::method();
// returns unexpected results:
// ['test1', 'rules', 'did', 'something'];
// should be:
// ['test2', 'rules', 'did', 'something'];

我可以在method()方法中使用一些讨厌的eval()来工作:

public static function method()
{
    if (!eval(''''.get_called_class().'::$returned;')) {
        static::$returned = static::doSomething();
    }   
    return static::$returned;
}

现在它简单地匹配它对'My'Namespaced'Class::$returned,但它也很奇怪,因为检查一个静态属性,$returned,这是定义在trait开始,并正确地绑定到使用它的类。那么为什么static::$returned不能工作?

那么为什么在这里使用延迟静态绑定呢?

试试这个

trait Example
{
    public static $returned;
    public static function method()
    {
        if (!self::$returned) {
            self::$returned = self::doSomething();
        }   
        return self::$returned;
    }
    public static function doSomething()
    {
        return array_merge(self::$rules, ['did', 'something']);
    }
}