Skip to content

Instantly share code, notes, and snippets.

@rahilwazir
Last active March 21, 2018 06:24
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 rahilwazir/028dd79efba321a2de1a to your computer and use it in GitHub Desktop.
Save rahilwazir/028dd79efba321a2de1a to your computer and use it in GitHub Desktop.
Access parent class private member from child class
<?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;
};

Usage:

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'));

Live Example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment