How can private methods be called from outside the class in PHP, and what are the limitations?

Private methods in PHP cannot be called directly from outside the class. One way to access private methods from outside the class is by using reflection. Reflection allows you to access and manipulate classes, objects, methods, and properties at runtime. However, it is important to note that accessing private methods from outside the class using reflection goes against the principles of encapsulation and can make your code harder to maintain.

class MyClass {
    private function privateMethod() {
        return 'This is a private method.';
    }
}

$object = new MyClass();

$method = new ReflectionMethod('MyClass', 'privateMethod');
$method->setAccessible(true);
echo $method->invoke($object); // Output: This is a private method.