0

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)?

1
  • What? ;) You can access all given arguments with func_get_args(). What are you trying to do? Commented Jan 13, 2013 at 19:03

1 Answer 1

2

You can use reflection when you get an instance of the class, and pass it an array of arguments, like this:

$ref = new ReflectionClass( $class);
$this->elements[($arguments[0] === HTML ? uniqid() : $arguments[1])] = $ref->newInstanceArgs( $parameters);

You also don't need this:

$parameters = null;

foreach (array_slice($arguments, 1) as $argument) {
     $parameters[] = (is_numeric($argument) ? $argument : "\"{$argument}\"");
}

You can replace the contents of that if statement with the above code placed after this:

$parameters = array_slice( $arguments, 1);
Sign up to request clarification or add additional context in comments.

1 Comment

Chapeau! Exactly what I was looking for. Thanks a million! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.