xref: /PHP-7.4/ext/reflection/tests/007.phpt (revision d679f022)
1--TEST--
2ReflectionClass::newInstance[Args]
3--FILE--
4<?php
5
6function test($class)
7{
8	echo "====>$class\n";
9	try
10	{
11		$ref = new ReflectionClass($class);
12	}
13	catch (ReflectionException $e)
14	{
15		var_dump($e->getMessage());
16		return; // only here
17	}
18
19	echo "====>newInstance()\n";
20	try
21	{
22		var_dump($ref->newInstance());
23	}
24	catch (ReflectionException $e)
25	{
26		var_dump($e->getMessage());
27	}
28	catch (Throwable $e)
29	{
30		echo "Exception: " . $e->getMessage() . "\n";
31	}
32
33	echo "====>newInstance(25)\n";
34	try
35	{
36		var_dump($ref->newInstance(25));
37	}
38	catch (ReflectionException $e)
39	{
40		var_dump($e->getMessage());
41	}
42
43	echo "====>newInstance(25, 42)\n";
44	try
45	{
46		var_dump($ref->newInstance(25, 42));
47	}
48	catch (ReflectionException $e)
49	{
50		var_dump($e->getMessage());
51	}
52
53	echo "\n";
54}
55
56spl_autoload_register(function ($class) {
57	echo __FUNCTION__ . "($class)\n";
58});
59
60test('Class_does_not_exist');
61
62Class NoCtor
63{
64}
65
66test('NoCtor');
67
68Class WithCtor
69{
70	function __construct()
71	{
72		echo __METHOD__ . "()\n";
73		var_dump(func_get_args());
74	}
75}
76
77test('WithCtor');
78
79Class WithCtorWithArgs
80{
81	function __construct($arg)
82	{
83		echo __METHOD__ . "($arg)\n";
84		var_dump(func_get_args());
85	}
86}
87
88test('WithCtorWithArgs');
89
90?>
91===DONE===
92<?php exit(0); ?>
93--EXPECTF--
94====>Class_does_not_exist
95{closure}(Class_does_not_exist)
96string(41) "Class Class_does_not_exist does not exist"
97====>NoCtor
98====>newInstance()
99object(NoCtor)#%d (0) {
100}
101====>newInstance(25)
102string(86) "Class NoCtor does not have a constructor, so you cannot pass any constructor arguments"
103====>newInstance(25, 42)
104string(86) "Class NoCtor does not have a constructor, so you cannot pass any constructor arguments"
105
106====>WithCtor
107====>newInstance()
108WithCtor::__construct()
109array(0) {
110}
111object(WithCtor)#%d (0) {
112}
113====>newInstance(25)
114WithCtor::__construct()
115array(1) {
116  [0]=>
117  int(25)
118}
119object(WithCtor)#%d (0) {
120}
121====>newInstance(25, 42)
122WithCtor::__construct()
123array(2) {
124  [0]=>
125  int(25)
126  [1]=>
127  int(42)
128}
129object(WithCtor)#%d (0) {
130}
131
132====>WithCtorWithArgs
133====>newInstance()
134Exception: Too few arguments to function WithCtorWithArgs::__construct(), 0 passed and exactly 1 expected
135====>newInstance(25)
136WithCtorWithArgs::__construct(25)
137array(1) {
138  [0]=>
139  int(25)
140}
141object(WithCtorWithArgs)#%d (0) {
142}
143====>newInstance(25, 42)
144WithCtorWithArgs::__construct(25)
145array(2) {
146  [0]=>
147  int(25)
148  [1]=>
149  int(42)
150}
151object(WithCtorWithArgs)#%d (0) {
152}
153
154===DONE===
155