Skip to content

Instantly share code, notes, and snippets.

@Dellos7
Created July 14, 2017 22:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dellos7/0040c453d86ed2838a845331d0c50473 to your computer and use it in GitHub Desktop.
Save Dellos7/0040c453d86ed2838a845331d0c50473 to your computer and use it in GitHub Desktop.
Helper class that allows to read private & protected properties from a specific object and also to invoke private & protected methods from a specific object
<?php
class AccessibilityClassHack {
/**
* Allows you to get the value of a protected or private property of an object
* @param $obj The class object of the property you want to get access to
* @param $prop The name of the property you want to get access to
* @return Returns the property $prop value of the object $obj
*/
public static function getProtectedOrPrivateProperty($obj, $prop) {
$reflection = new ReflectionClass($obj);
$property = $reflection->getProperty($prop);
$property->setAccessible(true);
return $property->getValue($obj);
}
/**
* Allows you to invoke a protected or private method of an object
* @param $obj The class object of the method you want to invoke
* @param $methodName The name of the method you want to invoke
* @return Returns the result of the execution of the method $methodName of the object $obj
*/
public static function invokeProtectedOrPrivateMethod($obj, $methodName, ...$paramsArray) {
$reflection = new ReflectionClass($obj);
$method = $reflection->getMethod($methodName);
$method->setAccessible(true);
return $method->invoke($obj, ...$paramsArray);
}
}
<?php
class MyAlmostPrivateClass {
private $privateProperty = 'private property';
private function privateMethod( $param1, $param2 ) {
return 'private method: ' . $param1 . ', ' . $param2;
}
}
require_once( 'AccessibilityClassHack.php' );
$myClassObj = new MyAlmostPrivateClass();
//This is not allowed :( (uncomment and see Fatal Error)
//$privatePropertyValue = $myClassObj->privateProperty
//This is allowed :)
$privatePropertyValue = AccessibilityClassHack::getProtectedOrPrivateProperty( $myClassObj, 'privateProperty' );
echo $privatePropertyValue;
//This is not allowed :( (uncomment and see Fatal Error)
//$privateMethodResult = $myClassObj->privateMethod( 'p1', 'p2' );
//This is allowed :)
$privateMethodResult = AccessibilityClassHack::invokeProtectedOrPrivateMethod( $myClassObj, 'privateMethod', 'p1', 'p2' );
echo '<br>';
echo $privateMethodResult;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment