ReflectionClass_newInstance_001.phpt 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. --TEST--
  2. ReflectionClass::newInstance()
  3. --CREDITS--
  4. Robin Fernandes <robinf@php.net>
  5. Steve Seear <stevseea@php.net>
  6. --FILE--
  7. <?php
  8. class A {
  9. public function A() {
  10. echo "In constructor of class A\n";
  11. }
  12. }
  13. class B {
  14. public function __construct($a, $b) {
  15. echo "In constructor of class B with args $a, $b\n";
  16. }
  17. }
  18. class C {
  19. protected function __construct() {
  20. echo "In constructor of class C\n";
  21. }
  22. }
  23. class D {
  24. private function __construct() {
  25. echo "In constructor of class D\n";
  26. }
  27. }
  28. class E {
  29. }
  30. $rcA = new ReflectionClass('A');
  31. $rcB = new ReflectionClass('B');
  32. $rcC = new ReflectionClass('C');
  33. $rcD = new ReflectionClass('D');
  34. $rcE = new ReflectionClass('E');
  35. $a1 = $rcA->newInstance();
  36. $a2 = $rcA->newInstance('x');
  37. var_dump($a1, $a2);
  38. $b1 = $rcB->newInstance();
  39. $b2 = $rcB->newInstance('x', 123);
  40. var_dump($b1, $b2);
  41. try {
  42. $rcC->newInstance();
  43. echo "you should not see this\n";
  44. } catch (Exception $e) {
  45. echo $e->getMessage() . "\n";
  46. }
  47. try {
  48. $rcD->newInstance();
  49. echo "you should not see this\n";
  50. } catch (Exception $e) {
  51. echo $e->getMessage() . "\n";
  52. }
  53. $e1 = $rcE->newInstance();
  54. var_dump($e1);
  55. try {
  56. $e2 = $rcE->newInstance('x');
  57. echo "you should not see this\n";
  58. } catch (Exception $e) {
  59. echo $e->getMessage() . "\n";
  60. }
  61. ?>
  62. --EXPECTF--
  63. In constructor of class A
  64. In constructor of class A
  65. object(A)#%d (0) {
  66. }
  67. object(A)#%d (0) {
  68. }
  69. Warning: Missing argument 1 for B::__construct() in %s on line 9
  70. Warning: Missing argument 2 for B::__construct() in %s on line 9
  71. Notice: Undefined variable: a in %s on line 10
  72. Notice: Undefined variable: b in %s on line 10
  73. In constructor of class B with args ,
  74. In constructor of class B with args x, 123
  75. object(B)#%d (0) {
  76. }
  77. object(B)#%d (0) {
  78. }
  79. Access to non-public constructor of class C
  80. Access to non-public constructor of class D
  81. object(E)#%d (0) {
  82. }
  83. Class E does not have a constructor, so you cannot pass any constructor arguments