ReflectionClass_newInstance_001.phpt 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. try {
  39. var_dump($rcB->newInstance());
  40. } catch (Throwable $e) {
  41. echo "Exception: " . $e->getMessage() . "\n";
  42. }
  43. try {
  44. var_dump($rcB->newInstance('x', 123));
  45. } catch (Throwable $e) {
  46. echo "Exception: " . $e->getMessage() . "\n";
  47. }
  48. try {
  49. $rcC->newInstance();
  50. echo "you should not see this\n";
  51. } catch (Exception $e) {
  52. echo $e->getMessage() . "\n";
  53. }
  54. try {
  55. $rcD->newInstance();
  56. echo "you should not see this\n";
  57. } catch (Exception $e) {
  58. echo $e->getMessage() . "\n";
  59. }
  60. $e1 = $rcE->newInstance();
  61. var_dump($e1);
  62. try {
  63. $e2 = $rcE->newInstance('x');
  64. echo "you should not see this\n";
  65. } catch (Exception $e) {
  66. echo $e->getMessage() . "\n";
  67. }
  68. ?>
  69. --EXPECTF--
  70. Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; A has a deprecated constructor in %s on line %d
  71. In constructor of class A
  72. In constructor of class A
  73. object(A)#%d (0) {
  74. }
  75. object(A)#%d (0) {
  76. }
  77. Exception: Too few arguments to function B::__construct(), 0 passed and exactly 2 expected
  78. In constructor of class B with args x, 123
  79. object(B)#%d (0) {
  80. }
  81. Access to non-public constructor of class C
  82. Access to non-public constructor of class D
  83. object(E)#%d (0) {
  84. }
  85. Class E does not have a constructor, so you cannot pass any constructor arguments