Call private methods and private properties from outside a class in PHP

Pablo López Torres picture Pablo López Torres · Apr 29, 2010 · Viewed 37.9k times · Source

I want to access private methods and variables from outside the classes in very rare specific cases.

I've seen that this is not be possible although introspection is used.

The specific case is the next one:

I would like to have something like this:

class Console
{
    final public static function run() {

        while (TRUE != FALSE) {
            echo "\n> ";
            $command = trim(fgets(STDIN));

            switch ($command) {
                case 'exit':
                case 'q':
                case 'quit':
                    echo "OK+\n";
                    return;
                default:
                    ob_start();
                    eval($command);
                    $out = ob_get_contents();
                    ob_end_clean();

                    print("Command: $command");
                    print("Output:\n$out");         

                    break;
            }
        }
    }
}

This method should be able to be injected in the code like this:

Class Demo
{
    private $a;

    final public function myMethod()
    {
        // some code
        Console::run();
        // some other code
    }

    final public function myPublicMethod()
    {
        return "I can run through eval()";
    }

    private function myPrivateMethod()
    {
        return "I cannot run through eval()";
    }
}

(this is just one simplification. the real one goes through a socket, and implement a bunch of more things...)

So...

If you instantiate the class Demo and you call $demo->myMethod(), you'll get a console: that console can access the first method writing a command like:

> $this->myPublicMethod();

But you cannot run successfully the second one:

> $this->myPrivateMethod();

Do any of you have any idea, or if there is any library for PHP that allows you to do this?

Thanks a lot!

Answer

webbiedave picture webbiedave · Apr 29, 2010

Just make the method public. But if you want to get tricky you can try this (PHP 5.3):

class LockedGate
{
    private function open()
    {
        return 'how did you get in here?!!';
    }
}

$object = new LockedGate();
$reflector = new ReflectionObject($object);
$method = $reflector->getMethod('open');
$method->setAccessible(true);
echo $method->invoke($object);