-
-
Save mouecom/393bdfe3b7ec6ae500e70b140db58a79 to your computer and use it in GitHub Desktop.
Get/set any class private property
This file contains hidden or 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 | |
/** | |
* Access/modify any instance private property. | |
*/ | |
class Undies { | |
protected $instance; | |
protected $setter; | |
protected $getter; | |
public function __construct($instance) | |
{ | |
$this->instance = $instance; | |
$this->getter = function($property) { return $this->{$property}; }; | |
$this->setter = function($property, $value) { $this->{$property} = $value; }; | |
} | |
public function __get($property) | |
{ | |
return $this->getter->call($this->instance, $property); | |
} | |
public function __set($property, $value) | |
{ | |
$this->setter->call($this->instance, $property, $value); | |
} | |
} | |
/** | |
* EXAMPLE: | |
* | |
* class Foo { | |
* private $privateProperty = "Hello"; | |
* } | |
* | |
* $foo = new Foo(); | |
* $undies = new Undies($foo); | |
* | |
* echo $undies->privateProperty; // Hello | |
* $undies->privateProperty = 'Goodbye'; | |
* echo $undies->privateProperty; // Goodbye | |
* | |
* Working example: https://3v4l.org/ib0HA | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment