1

staticキーワードが特性で何を返すのか疑問に思っていましたか? それを使用するクラスではなく、特性にバインドされているようです。例えば:

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'];

メソッドの厄介な部分で動作させることができeval()ましたmethod()

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

    return static::$returned;
}

今は単純に照合しますが、最初にトレイトで定義され、それを使用するクラスに正しくバインドされ\My\Namespaced\Class::$returnedた静的プロパティ をチェックするのも奇妙です。$returnedでは、なぜうまくいかないのstatic::$returnedでしょうか?

PHP のバージョンは 5.6.10 です。

4

1 に答える 1

0

では、なぜここで遅延静的バインディングを使用するのですか?

これを試して

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']);
    }
}
于 2015-07-25T19:10:56.987 に答える