class ParentClass {
private $foo = 123;
public function __construct() {}
}
$parent = new ParentClass();
class ChildClass extends ParentClass {
public function __construct() {
parent::__construct();
}
}
$child = new ChildClass();
var_dump(access_parent_private_member($child, 'foo'));
Last active
March 21, 2018 06:24
-
-
Save rahilwazir/028dd79efba321a2de1a to your computer and use it in GitHub Desktop.
Access parent class private member from child class
This file contains hidden or 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 | |
/** | |
* Access parent class private member from child class | |
* @param $class $this|object | |
* @param $property string | |
* @param $cache bool | |
* @return mixed | |
*/ | |
$cacheStorage = []; | |
function access_parent_private_member($class, $property, $cache = true) { | |
$class_name = get_parent_class($class); | |
if ($cache && isset($cacheStorage[$class_name], $cacheStorage[$class_name][$property]) && !empty($cacheStorage[$class_name])) { | |
return $cacheStorage[$class_name][$property]; | |
} | |
$closure = Closure::bind(function() use ($property) { | |
return $this->{$property}; | |
}, $class, $class_name); | |
$value = $closure(); | |
$cacheStorage[$class_name] = [$property => $value]; | |
return $value; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment