VisibilityHack
This file contains 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 | |
/** | |
* Tools for accessing "invisible" properties and calling "invisible" methods | |
* | |
* @author Jan Tvrdík | |
* @license MIT | |
*/ | |
class VisibilityHack | |
{ | |
/** | |
* Calls method | |
* | |
* @param string|object class name (for static methods) or class instance | |
* @param string method name | |
* @param array method parameters | |
* @return mixed value returned by method | |
*/ | |
public static function callMethod($object, $method, $params = array()) | |
{ | |
$reflection = new ReflectionMethod($object, $method); | |
$reflection->setAccessible(TRUE); | |
// $reflection->invokeArgs doesn't work with static methods | |
array_unshift($params, $object); | |
return call_user_func_array(array($reflection, 'invoke'), $params); | |
} | |
/** | |
* Reads property value | |
* | |
* @param string|object class name (for static properties) or class instance | |
* @param string property name | |
* @return mixed property value | |
*/ | |
public static function getPropertyValue($object, $property) | |
{ | |
$reflection = new ReflectionProperty($object, $property); | |
$reflection->setAccessible(TRUE); | |
return $reflection->getValue($object); | |
} | |
/** | |
* Sets property value | |
* | |
* @param string|object class name (for static properties) or class instance | |
* @param string property name | |
* @param mixed new property value | |
* @return void | |
*/ | |
public static function setPropertyValue($object, $property, $value) | |
{ | |
$reflection = new ReflectionProperty($object, $property); | |
$reflection->setAccessible(TRUE); | |
$reflection->setValue($object, $value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment