Created
September 14, 2011 16:02
-
-
Save mendelgusmao/1216960 to your computer and use it in GitHub Desktop.
Instantiating a class with full parameter list using eval()
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 | |
error_reporting(E_ALL); | |
function _new ($class_name, $constructor_parameters) { | |
$parameters = array(); | |
$values = array_values($constructor_parameters); | |
// Another approach: for ($index = 0; $index < count($values); $index++) | |
foreach (array_keys($values) as $index) | |
$parameters[] = "\$values[{$index}]"; | |
$parameters = implode(", ", $parameters); | |
return eval("\return new $class_name($parameters);"); | |
} | |
class wtf { | |
function __construct() { | |
$args = func_get_args(); | |
echo __CLASS__, " instanced\n"; | |
print_r($args); | |
} | |
function fun() { | |
echo __FUNCTION__, " called\n"; | |
} | |
} | |
$wtf = _new("wtf", array("foo", "bar", "baz")); | |
$wtf->fun(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment