ReflectionClass_newInstance_001.phpt 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 B {
  9. public function __construct($a, $b) {
  10. echo "In constructor of class B with args $a, $b\n";
  11. }
  12. }
  13. class C {
  14. protected function __construct() {
  15. echo "In constructor of class C\n";
  16. }
  17. }
  18. class D {
  19. private function __construct() {
  20. echo "In constructor of class D\n";
  21. }
  22. }
  23. class E {
  24. }
  25. $rcB = new ReflectionClass('B');
  26. $rcC = new ReflectionClass('C');
  27. $rcD = new ReflectionClass('D');
  28. $rcE = new ReflectionClass('E');
  29. try {
  30. var_dump($rcB->newInstance());
  31. } catch (Throwable $e) {
  32. echo "Exception: " . $e->getMessage() . "\n";
  33. }
  34. try {
  35. var_dump($rcB->newInstance('x', 123));
  36. } catch (Throwable $e) {
  37. echo "Exception: " . $e->getMessage() . "\n";
  38. }
  39. try {
  40. $rcC->newInstance();
  41. echo "you should not see this\n";
  42. } catch (Exception $e) {
  43. echo $e->getMessage() . "\n";
  44. }
  45. try {
  46. $rcD->newInstance();
  47. echo "you should not see this\n";
  48. } catch (Exception $e) {
  49. echo $e->getMessage() . "\n";
  50. }
  51. $e1 = $rcE->newInstance();
  52. var_dump($e1);
  53. try {
  54. $e2 = $rcE->newInstance('x');
  55. echo "you should not see this\n";
  56. } catch (Exception $e) {
  57. echo $e->getMessage() . "\n";
  58. }
  59. ?>
  60. --EXPECTF--
  61. Exception: Too few arguments to function B::__construct(), 0 passed and exactly 2 expected
  62. In constructor of class B with args x, 123
  63. object(B)#%d (0) {
  64. }
  65. Access to non-public constructor of class C
  66. Access to non-public constructor of class D
  67. object(E)#%d (0) {
  68. }
  69. Class E does not have a constructor, so you cannot pass any constructor arguments