Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Instantiating a class with full parameter list using eval()
<?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