assign_coalesce_002.phpt 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. --TEST--
  2. Coalesce assign (??=): Exception handling
  3. --FILE--
  4. <?php
  5. $foo = "fo";
  6. $foo .= "o";
  7. $bar = "ba";
  8. $bar .= "r";
  9. function id($arg) {
  10. echo "id($arg)\n";
  11. return $arg;
  12. }
  13. function do_throw($msg) {
  14. throw new Exception($msg);
  15. }
  16. $ary = [];
  17. try {
  18. $ary[id($foo)] ??= do_throw("ex1");
  19. } catch (Exception $e) {
  20. echo $e->getMessage(), "\n";
  21. }
  22. var_dump($ary);
  23. class AA implements ArrayAccess {
  24. public function offsetExists($k): bool {
  25. return true;
  26. }
  27. public function &offsetGet($k): mixed {
  28. $var = ["foo" => "bar"];
  29. return $var;
  30. }
  31. public function offsetSet($k,$v): void {}
  32. public function offsetUnset($k): void {}
  33. }
  34. class Dtor {
  35. public function __destruct() {
  36. throw new Exception("dtor");
  37. }
  38. }
  39. $ary = new AA;
  40. try {
  41. $ary[new Dtor][id($foo)] ??= $bar;
  42. } catch (Exception $e) {
  43. echo $e->getMessage(), "\n";
  44. }
  45. var_dump($foo);
  46. class AA2 implements ArrayAccess {
  47. public function offsetExists($k): bool {
  48. return false;
  49. }
  50. public function offsetGet($k): mixed {
  51. return null;
  52. }
  53. public function offsetSet($k,$v): void {}
  54. public function offsetUnset($k): void {}
  55. }
  56. $ary = ["foo" => new AA2];
  57. try {
  58. $ary[id($foo)][new Dtor] ??= $bar;
  59. } catch (Exception $e) {
  60. echo $e->getMessage(), "\n";
  61. }
  62. var_dump($foo);
  63. ?>
  64. --EXPECT--
  65. id(foo)
  66. ex1
  67. array(0) {
  68. }
  69. id(foo)
  70. dtor
  71. string(3) "foo"
  72. id(foo)
  73. dtor
  74. string(3) "foo"