class MyClass { private function myPrivateMethod() { echo "This is a private method."; } } $myClass = new MyClass(); $reflection = new ReflectionMethod('MyClass', 'myPrivateMethod'); $reflection->setAccessible(true); $reflection->invoke($myClass); // Output: This is a private method.
class MyClass { protected function myProtectedMethod() { echo "This is a protected method."; } } class MyChildClass extends MyClass { public function callProtectedMethod() { $reflection = new ReflectionMethod('MyClass', 'myProtectedMethod'); $reflection->setAccessible(true); $reflection->invoke($this); // Output: This is a protected method. } } $myChildClass = new MyChildClass(); $myChildClass->callProtectedMethod();In this example, we define a protected `myProtectedMethod()` method in the `MyClass` class and then define a child class called `MyChildClass` that extends `MyClass`. We then define a method in the child class called `callProtectedMethod()` which creates a `ReflectionMethod` object for the protected method and sets it to accessible. We then invoke the `myProtectedMethod()` method using `$reflection->invoke($this)` which outputs "This is a protected method." The package/library for `ReflectionMethod` class is "PHP Core".