initialization_scope.phpt 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. --TEST--
  2. Initialization can only happen from private scope
  3. --FILE--
  4. <?php
  5. class A {
  6. public readonly int $prop;
  7. public function initPrivate() {
  8. $this->prop = 3;
  9. }
  10. }
  11. class B extends A {
  12. public function initProtected() {
  13. $this->prop = 2;
  14. }
  15. }
  16. $test = new B;
  17. try {
  18. $test->prop = 1;
  19. } catch (Error $e) {
  20. echo $e->getMessage(), "\n";
  21. }
  22. try {
  23. $test->initProtected();
  24. } catch (Error $e) {
  25. echo $e->getMessage(), "\n";
  26. }
  27. $test->initPrivate();
  28. var_dump($test->prop);
  29. // Rebinding bypass works.
  30. $test = new B;
  31. (function() {
  32. $this->prop = 1;
  33. })->bindTo($test, A::class)();
  34. var_dump($test->prop);
  35. class C extends A {
  36. public readonly int $prop;
  37. }
  38. $test = new C;
  39. $test->initPrivate();
  40. var_dump($test->prop);
  41. class X {
  42. public function initFromParent() {
  43. $this->prop = 1;
  44. }
  45. }
  46. class Y extends X {
  47. public readonly int $prop;
  48. }
  49. $test = new Y;
  50. try {
  51. $test->initFromParent();
  52. } catch (Error $e) {
  53. echo $e->getMessage(), "\n";
  54. }
  55. ?>
  56. --EXPECT--
  57. Cannot initialize readonly property A::$prop from global scope
  58. Cannot initialize readonly property A::$prop from scope B
  59. int(3)
  60. int(1)
  61. int(3)
  62. Cannot initialize readonly property Y::$prop from scope X