Last active
March 15, 2024 13:02
-
-
Save tgeorgel/4370b105ebb6d02908f000f84ac47562 to your computer and use it in GitHub Desktop.
Invade PHP class easily (no dependancy)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if (!function_exists('invade')) : | |
/** | |
* Invade a class to access its private methods and properties. | |
*/ | |
function invade($target): InvadeProxy | |
{ | |
return new InvadeProxy($target); | |
} | |
endif; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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