Skip to content

Instantly share code, notes, and snippets.

@mouecom
Forked from jszobody/Undies.php
Created February 12, 2022 15:59
Show Gist options
  • Save mouecom/393bdfe3b7ec6ae500e70b140db58a79 to your computer and use it in GitHub Desktop.
Save mouecom/393bdfe3b7ec6ae500e70b140db58a79 to your computer and use it in GitHub Desktop.
Get/set any class private property
<?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