Skip to content

Instantly share code, notes, and snippets.

@tanakahisateru
Created December 13, 2017 14:04
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 tanakahisateru/e51067894774be92306ffb12a721e75a to your computer and use it in GitHub Desktop.
Save tanakahisateru/e51067894774be92306ffb12a721e75a to your computer and use it in GitHub Desktop.
継承で子が親の private にアクセスするできるようにするやつ
<?php
trait AncestorPrivateAccessTrait
{
protected function invokePrivateMethod($name, $arguments = [])
{
$reflectionClass = new \ReflectionClass(get_class($this));
while (!$reflectionClass->hasMethod($name)) {
$reflectionClass = $reflectionClass->getParentClass();
if (!$reflectionClass) {
throw new \InvalidArgumentException('Property not found:' . $name);
}
}
$method = $reflectionClass->getMethod($name);
$method->setAccessible(true);
array_unshift($arguments, $this);
return call_user_func_array([$method, 'invoke'], $arguments);
}
protected function getPrivateProperty($name)
{
$reflectionClass = new \ReflectionClass(get_class($this));
while (!$reflectionClass->hasProperty($name)) {
$reflectionClass = $reflectionClass->getParentClass();
if (!$reflectionClass) {
throw new \InvalidArgumentException('Property not found:' . $name);
}
}
$property = $reflectionClass->getProperty($name);
$property->setAccessible(true);
return $property->getValue($this);
}
protected function setPrivateProperty($name, $value)
{
$reflectionClass = new \ReflectionClass(get_class($this));
while (!$reflectionClass->hasProperty($name)) {
$reflectionClass = $reflectionClass->getParentClass();
if (!$reflectionClass) {
throw new \InvalidArgumentException('Property not found:' . $name);
}
}
$property = $reflectionClass->getProperty($name);
$property->setAccessible(true);
$property->setValue($this, $value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment