Skip to content

Instantly share code, notes, and snippets.

@juampi92
Created February 5, 2022 20:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juampi92/4eec2a0ed225973222b9154a6ca7c671 to your computer and use it in GitHub Desktop.
Save juampi92/4eec2a0ed225973222b9154a6ca7c671 to your computer and use it in GitHub Desktop.
Testing private methods properties
<?php
if (!function_exists('private_access')) {
function private_access(object $object)
{
return new PrivateAccess($object);
}
}
<?php
namespace Tests\Support;
use ReflectionClass;
use ReflectionException;
use ReflectionObject;
class PrivateAccess
{
public function __construct(
private object $object,
) {
}
/**
* @throws ReflectionException
*/
public function __call(string $methodName, array $arguments): mixed
{
$class = new ReflectionClass($this->object);
$method = $class->getMethod($methodName);
$method->setAccessible(true);
return $method->invokeArgs($this->object, $arguments);
}
/**
* @throws ReflectionException
*/
public function __get(string $name): mixed
{
$class = new ReflectionObject($this->object);
$property = $class->getProperty($name);
$property->setAccessible(true);
return $property->getValue($this->object);
}
/**
* @throws ReflectionException
*/
public function __set(string $name, mixed $value): void
{
$reflection = new ReflectionClass($this->object);
$reflectionProperty = $reflection->getProperty($name);
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($this->object, $value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment