Private Access

Packagist GitLab GitHub Bitbucket Gitea

A small simple library to access private properties of the objects. Actually it’s more an example of mad skillz than a useful tool. No Reflection API calls!


Use composer:

composer require arokettu/private-access --dev

Why --dev?

This library may be used for debugging or with PHP consoles like PsySH. If you are actually using it in some live system, you’re doing something terribly wrong.


These four simple functions can come in handy as helpers for something like PsySH


All functions also work with protected and public visibilities

Class examples:


class A extends B
    private const SECRET_CONST = '';
    private $secret;
    private static $staticSecret;
    private function doStuff() {}
    private static function doStaticStuff() {}

class B
    private $secret;
    private function doStuff() {}

$a = new A();


Get value of a private field


use function Arokettu\Debug\get_private_field;

get_private_field($a, 'secret'); // get $a->A::secret value
get_private_field(A::class, 'staticSecret'); // get A::$staticSecret value
get_private_field([$a, B::class], 'secret'); // get $a->B::$secret value


Set value of a private field


use function Arokettu\Debug\set_private_field;

set_private_field($a, 'secret', 'new secret'); // set new $a->A::secret value
set_private_field(A::class, 'staticSecret', 'new secret'); // set new A::$staticSecret value
set_private_field([$a, B::class], 'secret', 'new secret'); // set new $a->B::$secret value


Call private method


use function Arokettu\Debug\call_private_method;

call_private_method($a, 'doStuff', 'whatever'); // call $a->A::doStuff('whatever')
call_private_method(A::class, 'doStaticStuff', 'whatever'); // call A::doStaticStuff('whatever')
call_private_method([$a, B::class], 'doStuff', 'whatever'); // call $a->B::doStuff('whatever')


Get value of a private constant


This function works in all supported PHP versions but is useful only with PHP 7.1+ where constants can be private or protected


use function Arokettu\Debug\get_private_const;

get_private_const($a, 'SECRET_CONST');
// or
get_private_const(A::class, 'SECRET_CONST');


The library is available as open source under the terms of the MIT License.