1--TEST--
2ReflectionMethod::invoke()
3--FILE--
4<?php
5
6class TestClass {
7    public $prop = 2;
8
9    public function foo() {
10        echo "Called foo(), property = $this->prop\n";
11        var_dump($this);
12        return "Return Val";
13    }
14
15    public function willThrow() {
16        throw new Exception("Called willThrow()");
17    }
18
19    public function methodWithArgs($a, $b) {
20        echo "Called methodWithArgs($a, $b)\n";
21    }
22
23    public static function staticMethod() {
24        echo "Called staticMethod()\n";
25        try {
26            var_dump($this);
27        } catch (Throwable $e) {
28            echo "Exception: " . $e->getMessage() . "\n";
29        }
30    }
31
32    private static function privateMethod() {
33        echo "Called privateMethod()\n";
34    }
35}
36
37abstract class AbstractClass {
38    abstract function foo();
39}
40
41$foo = new ReflectionMethod('TestClass', 'foo');
42$methodWithArgs = new ReflectionMethod('TestClass', 'methodWithArgs');
43$staticMethod = new ReflectionMethod('TestClass::staticMethod');
44$privateMethod = new ReflectionMethod("TestClass::privateMethod");
45$methodThatThrows = new ReflectionMethod("TestClass::willThrow");
46
47$testClassInstance = new TestClass();
48$testClassInstance->prop = "Hello";
49
50echo "Public method:\n";
51
52var_dump($foo->invoke($testClassInstance));
53
54var_dump($foo->invoke($testClassInstance, true));
55
56echo "\nMethod with args:\n";
57
58var_dump($methodWithArgs->invoke($testClassInstance, 1, "arg2"));
59var_dump($methodWithArgs->invoke($testClassInstance, 1, "arg2", 3));
60
61echo "\nStatic method:\n";
62
63try {
64    var_dump($staticMethod->invoke());
65} catch (TypeError $e) {
66    echo $e->getMessage(), "\n";
67}
68try {
69    var_dump($staticMethod->invoke(true));
70} catch (TypeError $e) {
71    echo $e->getMessage(), "\n";
72}
73var_dump($staticMethod->invoke(new stdClass()));
74
75echo "\nMethod that throws an exception:\n";
76try {
77    var_dump($methodThatThrows->invoke($testClassInstance));
78} catch (Exception $exc) {
79    var_dump($exc->getMessage());
80}
81
82?>
83--EXPECTF--
84Public method:
85Called foo(), property = Hello
86object(TestClass)#%d (1) {
87  ["prop"]=>
88  string(5) "Hello"
89}
90string(10) "Return Val"
91Called foo(), property = Hello
92object(TestClass)#%d (1) {
93  ["prop"]=>
94  string(5) "Hello"
95}
96string(10) "Return Val"
97
98Method with args:
99Called methodWithArgs(1, arg2)
100NULL
101Called methodWithArgs(1, arg2)
102NULL
103
104Static method:
105ReflectionMethod::invoke() expects at least 1 argument, 0 given
106ReflectionMethod::invoke(): Argument #1 ($object) must be of type ?object, bool given
107Called staticMethod()
108Exception: Using $this when not in object context
109NULL
110
111Method that throws an exception:
112string(18) "Called willThrow()"
113