I have a public method for creating sub-elements in my framework called addElement() which is defined as follows:
// addElement - adds an element (experimental version)
public function addElement() {
if ($arguments = func_get_args()) {
$class = "\\UI\\{$arguments[0]}";
if (func_num_args() > 1) {
$parameters = null;
foreach (array_slice($arguments, 1) as $argument) {
$parameters[] = (is_numeric($argument) ? $argument : "\"{$argument}\"");
}
$this->elements[($arguments[0] === HTML ? uniqid() : $arguments[1])] = new $class(implode(", ", $parameters));
}
}
}
and it gets called like this:
$article1 = new \UI\Article("article1");
$article->addElement(\UI\Aside, "aside1");
or, alternatively (depending on if you need direct access to the new element):
$article1 = new \UI\Article("article1");
$aside1 = $article->addElement(\UI\Aside, "aside1");
The problem comes when I use a method accepting more than two arguments (the type of element and its name, internal-wise), and it’s this:
$article1 = new \UI\Article("article1");
$article1->addElement(\UI\Abbreviation, "abbr1", "RAM", "Random Access Memory");
Using this method, the arguments passed to the function are, literally:
"abbr1", "RAM", "Random Access Memory"
My intention was for this string to be passed like if you were normally passing arguments to a given function. How can I perform that (it’s ok if I need to re-structure the function, although I would ideally like to just add the missing bits, if it’s correct to proceed like this)?
You can use reflection when you get an instance of the class, and pass it an array of arguments, like this:
You also don’t need this:
You can replace the contents of that
ifstatement with the above code placed after this: