This spatie/invade package offers an invade
function that will allow you to read/write private properties of an object. It will also allow you to call private methods.
Installation
You can install the package via composer:
composer require spatie/invade
Usage
Imagine you have this class defined which has a private property and method.
class MyClass
{
private string $privateProperty = 'private value';
private function privateMethod(): string
{
return 'private return value';
}
}
$myClass = new Myclass();
This is how you can get the value of the private property using the invade
function.
invade($myClass)->privateProperty; // returns 'private value'
The invade
function also allows you to change private values.
invade($myClass)->privateProperty = 'changed value';
invade($myClass)->privateProperty; // returns 'changed value
Using invade
you can also call private functions.
invade($myClass)->privateMethod(); // returns 'private return value'
Making PHPStan understand Invade
PHPStan will report errors for every invaded private method and property as it is not aware that you can now access them. To remove these errors install the PHPStan extension installer or add the invade PHPStan extension manually to your PHPStan configuration:
includes:
- ./vendor/spatie/invade/phpstan-extension.neon
Testing
composer test
vendor/bin/phpstan analyse -c types/phpstan.neon.dist
Leave a Reply