13
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHP: trait由来の静的プロパティはミックスインした時点の値で束縛される

Posted at
// トレイトを定義する
trait T {
    public static $value = 0;
}
assert([T::$value] === [0]);

// クラスAが定義され、トレイトがミックスインされる
class A {
    use T; // A::$value = 0で束縛
}
assert([T::$value, A::$value] === [0, 0]);

// トレイトの状態を変える
T::$value = 1; // Aクラスには影響しない
assert([T::$value, A::$value] === [1, 0]); 

// クラスBが定義され、トレイトがミックスインされる
class B {
    use T; // B::$value = 1で束縛
}
assert([T::$value, A::$value, B::$value] === [1, 0, 1]);

// トレイトの状態をもとに戻す
T::$value = 0; // A,Bクラスともに影響しない
assert([T::$value, A::$value, B::$value] === [0, 0, 1]);
13
9
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?