self_static_accessor.rst 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. =============================
  2. Rule ``self_static_accessor``
  3. =============================
  4. Inside an enum or ``final``/anonymous class, ``self`` should be preferred over
  5. ``static``.
  6. Examples
  7. --------
  8. Example #1
  9. ~~~~~~~~~~
  10. .. code-block:: diff
  11. --- Original
  12. +++ New
  13. <?php
  14. final class Sample
  15. {
  16. private static $A = 1;
  17. public function getBar()
  18. {
  19. - return static::class.static::test().static::$A;
  20. + return self::class.self::test().self::$A;
  21. }
  22. private static function test()
  23. {
  24. return 'test';
  25. }
  26. }
  27. Example #2
  28. ~~~~~~~~~~
  29. .. code-block:: diff
  30. --- Original
  31. +++ New
  32. <?php
  33. final class Foo
  34. {
  35. public function bar()
  36. {
  37. - return new static();
  38. + return new self();
  39. }
  40. }
  41. Example #3
  42. ~~~~~~~~~~
  43. .. code-block:: diff
  44. --- Original
  45. +++ New
  46. <?php
  47. final class Foo
  48. {
  49. public function isBar()
  50. {
  51. - return $foo instanceof static;
  52. + return $foo instanceof self;
  53. }
  54. }
  55. Example #4
  56. ~~~~~~~~~~
  57. .. code-block:: diff
  58. --- Original
  59. +++ New
  60. <?php
  61. $a = new class() {
  62. public function getBar()
  63. {
  64. - return static::class;
  65. + return self::class;
  66. }
  67. };
  68. Example #5
  69. ~~~~~~~~~~
  70. .. code-block:: diff
  71. --- Original
  72. +++ New
  73. <?php
  74. enum Foo
  75. {
  76. public const A = 123;
  77. public static function bar(): void
  78. {
  79. - echo static::A;
  80. + echo self::A;
  81. }
  82. }
  83. Rule sets
  84. ---------
  85. The rule is part of the following rule set:
  86. - `@PhpCsFixer <./../../ruleSets/PhpCsFixer.rst>`_