- array_shift: documentation ( source)
<?php
class Translator1
{
private $translator2;
public function __construct(Translator2 $t2)
{
$this->translator2 = $t2;
}
}
class Translator2
{
private $translator3;
public function __construct(Translator3 $t3)
{
$this->translator3 = $t3;
}
}
class Translator3 extends ParentTranslator
{
// none found, look for 'x' in parent class
}
class ParentTranslator {
private $x = 'LOL';
public function __construct()
{
$this->x = 'LOL';
}
}
function accessPrivatePropertyOf($object, ...$properties)
{
if (empty($properties))
{
return $object;
}
$reflector = new \ReflectionClass($object);
$property = array_shift($properties);
echo 'Looking in: ' . (is_object($object) ? get_class($object) : gettype($object)) . ' for property: ' . $property . PHP_EOL;
if (!$reflector->hasProperty($property))
{
/** Try parent class **/
$parent = $reflector->getParentClass();
echo 'BUT... does not exist, looking in parent: ' . $object->getName() . ' instead...' . PHP_EOL;
if (!$parent->hasProperty($property))
{
throw new \Exception;
}
$prop = $parent->getProperty($property);
$prop->setAccessible(true);
$property = $prop->getValue($object);
echo 'We found property with name: ' . $prop->getName() . ' and value: ' . $prop->getValue($object) . PHP_EOL;
return accessPrivatePropertyOf($property, ...$properties);
}
$prop = $reflector->getProperty($property);
$prop->setAccessible(true);
$property = $prop->getValue($object);
return accessPrivatePropertyOf($property, ...$properties);
}
$t = new Translator1(new Translator2(new Translator3));
// Shows no value for x WHYY?Y??
accessPrivatePropertyOf($t, 'translator2', 'translator3', 'x');