Created
November 7, 2016 23:30
-
-
Save bryanjhv/e1125db469d656761acbdb1c3c302ce6 to your computer and use it in GitHub Desktop.
Get private variable of object in PHP 5.3+
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 | |
/** | |
* 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; | |
} |
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 | |
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