Last active
December 29, 2015 17:29
-
-
Save sadams/7704467 to your computer and use it in GitHub Desktop.
A very edge case in PHP 5.4 regarding passing objects by reference and using reflection.
This file contains 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 | |
/** | |
* A very edge case in PHP 5.4 regarding passing objects by reference. | |
* It seems to be a compound effect of using reflection to set an inherited method as 'available', | |
* AND that method taking an explicitly referential argument (&argument sig) | |
* AND then invoking it with func_get_args() as opposed to constructing the array of args manually. | |
* | |
* No idea why these things all cause this behaviour or if they should. | |
* | |
* Important to note that this effect isn't present in PHP 5.5. | |
*/ | |
class A { | |
private function foo(&$arg1) { | |
var_dump('arg1: ', $arg1); | |
} | |
} | |
class B extends A { | |
public function bar() { | |
$x = new stdClass(); | |
$x->baz = 'just a value'; | |
$this->callPrivate($x); | |
} | |
private function callPrivate($x) | |
{ | |
$method = new \ReflectionMethod( | |
'A', | |
'foo' | |
); | |
//* for some reason, the private function needs to have been changed to be 'accessible' for this to work in 5.4 | |
$method->setAccessible(true); | |
//working 5.4 (* see above) but not in 5.5 | |
$arguments = func_get_args(); | |
//not working in either | |
$arguments = array($x); // <---- COMMENT THIS LINE TO SEE IT WORK IN PHP 5.4 | |
return $method->invokeArgs($this, $arguments); | |
} | |
} | |
$y = new B(); | |
$y->bar(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment