Junior — Middle
How can you invoke private class methods from external code?
sobes.tech AI
Answer from AI
In PHP, class private methods are not accessible directly from external code, but there are several ways to invoke them:
- Using Reflection API — allows access to private methods and calling them:
class MyClass {
private function secret() {
return "Secret method";
}
}
$obj = new MyClass();
$reflection = new ReflectionClass($obj);
$method = $reflection->getMethod('secret');
$method->setAccessible(true); // Makes the method accessible
echo $method->invoke($obj); // Will output: Secret method
-
Calling through a public method inside the class — if there is a public method that calls the private one.
-
Inheritance and overriding (limited) — but private methods are not inherited directly.
Most often, Reflection is used for testing or bypassing restrictions.