Created
December 13, 2017 14:04
-
-
Save tanakahisateru/e51067894774be92306ffb12a721e75a to your computer and use it in GitHub Desktop.
継承で子が親の private にアクセスするできるようにするやつ
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 | |
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