How can I get the variable $components out of this class and private function:
class WPCF7_Mail {
private function compose() {
return $components;
}
}
This is my best attempt:
class test extends WPCF7_Mail {
function compose( $send = true ) {
global $components;
}
}
new test();
global $components;
echo $components;
But I keep getting:
Fatal error: Call to private WPCF7_Mail::__construct() from invalid context
Edit: I cannot modify the class WPCF7_Mail. So I cannot make the function compose public.
You can get the private property or call a private function by using ReflectionClass::newInstanceWithoutConstructor() and Closure::bind().
Make sure that WPCF7_Mail is in the same Namespace, otherwise you'll need to provide the full namespace name (e.g '\Full\Namespace\WPCF7_Mail'
).
If you don't have a private/protected constructor with required parameters, you can simply use the class and Closure::bind()
.
$class = (new ReflectionClass('WPCF7_Mail'))->newInstanceWithoutConstructor();
$getter = function ($a) {
return $a->components;
};
$getter = Closure::bind($getter, null, $class);
var_dump($getter($class));
If you need to call the function, you can do it like this:
$class = (new ReflectionClass('WPCF7_Mail'))->newInstanceWithoutConstructor();
$getter = function ($a) {
return $a->compose();
};
$getter = Closure::bind($getter, null, $class);
var_dump($getter($class));
Note that this will work starting with php version 5.4