Skip to content

Instantly share code, notes, and snippets.

@jszobody
Last active February 12, 2022 15:59
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jszobody/ac506ee80707ee91028566442f58c9ec to your computer and use it in GitHub Desktop.
Save jszobody/ac506ee80707ee91028566442f58c9ec 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
*/
@mouecom
Copy link

mouecom commented Feb 12, 2022

Wow, learning something new. Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment