PHP Access Private Methods and Fields
These two simple functions can come in handy as helpers for something like PsySH. PHP >= 7.0 is required.
Call private method of an object:
<?php function call_private_method($object, string $method, ...$args) { return (function ($method, ...$args) { return call_user_func_array([$this, $method], $args); })->call($object, $method, ...$args); }
Get private field of an object:
<?php function get_private_field($object, string $field) { return (function ($field) { return $this->$field; })->call($object, $field); }
Example:
<?php class A { private $secret = 'SECRET234'; private function doStuff($whatever) { return $whatever . '!'; } } $a = new A; get_private_field($a, 'secret'); // SECRET234 call_private_method($a, 'doStuff', 'whatever'); // whatever!
UPD: "Why not make a library out of it", I thought. So it's now a library: https://sandfox.dev/php/private-access.html
Comments
Comments powered by Disqus