Skip to content

Instantly share code, notes, and snippets.

@tgeorgel
Last active March 15, 2024 13:02
Show Gist options
  • Save tgeorgel/4370b105ebb6d02908f000f84ac47562 to your computer and use it in GitHub Desktop.
Save tgeorgel/4370b105ebb6d02908f000f84ac47562 to your computer and use it in GitHub Desktop.
Invade PHP class easily (no dependancy)
<?php
if (!function_exists('invade')) :
/**
* Invade a class to access its private methods and properties.
*/
function invade($target): InvadeProxy
{
return new InvadeProxy($target);
}
endif;
<?php
namespace App;
class InvadeProxy
{
public function __construct(
public $target,
) {}
public function __call($method, $args)
{
$fn = fn ($method, $args) => $this->{$method}(...$args);
return $fn->call($this->target, $method, $args);
}
public function __get($property)
{
$fn = fn ($property) => $this->{$property};
return $fn->call($this->target, $property);
}
public function __set($property, $value)
{
$fn = fn ($property, $value) => $this->{$property} = $value;
return $fn->call($this->target, $property, $value);
}
}
// usage:
class PrivateClass
{
private $secret = 'lorem';
private function cantTouchThis()
{
return "oh snap, i've been invaded!";
}
}
$private = new PrivateClass();
invade($private)->secret; // 'lorem'
invade($private)->cantTouchThis(); // "oh snap, i've been invaded!"
invade($private)->secret = 'ipsum'; // $secret === 'ipsum'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment