Last active
October 22, 2015 08:24
-
-
Save dogmatic69/1bce2f12bfe21767aa11 to your computer and use it in GitHub Desktop.
calling private methods in a class through a proxy class using closure binding.
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 | |
/** | |
* Class with private methods that you need to access | |
*/ | |
class Something { | |
private function _wtf() { | |
return 'yey'; | |
} | |
private function _really() { | |
return 'yip'; | |
} | |
} | |
/** | |
* The muscles | |
*/ | |
class PrivateAccess { | |
/** | |
* instance of the class with private properties to be accessed | |
* | |
* @var Object | |
*/ | |
protected $_obj; | |
/** | |
* Constructor | |
* | |
* @param Object $obj the object that will be used | |
*/ | |
public function __construct($obj) { | |
$this->_obj = $obj; | |
} | |
/** | |
* magic call method to proxy calls to the passed object | |
* | |
* @param string $method the method being called | |
* @param array $args args passed to themethod | |
* | |
* @return mixed | |
*/ | |
public function __call($method, $args = array()) { | |
$closure = function($method, $args = array()) { | |
return call_user_func_array(array($this, $method), $args); | |
}; | |
$return = Closure::bind($closure, $this->_obj, get_class($this->_obj)); | |
return $return($method, $args); | |
} | |
} | |
$Class = new PrivateAccess(new Something()); | |
pr($Class->_wtf()); | |
pr($Class->_really()); |
the first version I had the public still in, but its gone now.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There are currently still
public
in your code.