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!
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();
We can call the private method of a class from another class in Java (which are defined using the private access modifier in Java). We can do this by changing the runtime behavior of the class by using some predefined methods of Java. For accessing private method of different class we will use Reflection API.
You need to add interface IF_ALV_RM_GRID_FRIEND into the class where you want to use private methods of CL_GUI_ALV_GRID. Once you've done that and you have inside an attribute of type CL_GUI_ALV_GRID then you can access its private and protected elements.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With