Pablo López Torres Pablo López Torres - 4 months ago 34
PHP Question

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

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";
$out = ob_get_contents();

print("Command: $command");


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

Class Demo
private $a;

final public function myMethod()
// some code
// 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...)


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!


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');
echo $method->invoke($object);