Skip to content

Instantly share code, notes, and snippets.

@JanTvrdik
Created May 9, 2010 20:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JanTvrdik/395371 to your computer and use it in GitHub Desktop.
Save JanTvrdik/395371 to your computer and use it in GitHub Desktop.
VisibilityHack
<?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