Skip to content

Instantly share code, notes, and snippets.

@bryanjhv
Created November 7, 2016 23:30
Show Gist options
  • Save bryanjhv/e1125db469d656761acbdb1c3c302ce6 to your computer and use it in GitHub Desktop.
Save bryanjhv/e1125db469d656761acbdb1c3c302ce6 to your computer and use it in GitHub Desktop.
Get private variable of object in PHP 5.3+
<?php
/**
* Get a private variable from any object.
*
* @param mixed $obj
* @param string $name
* @return mixed
*/
function get_private_var($obj, $name) {
$reflected = new ReflectionClass(get_class($obj));
$property = $reflected->getProperty($name);
$property->setAccessible(true);
$value = $property->getValue($obj);
$property->setAccessible(false);
return $value;
}
<?php
class User {
public $username;
private $password;
public function __construct($username, $password) {
$this->username = $username;
$this->password = $password;
}
}
$me = new User('dummy', 'secret');
// This will fail, Fatal error
$password = $me->password;
// But this will work
$password = get_private_var($me, 'password');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment