2

A simple question:

What is the syntax for creating a function with unlimited* arguments in PHP?

Example (ActionScript 3):

function multiTrace(...arguments):void
{
    var i:String;
    for each(i in arguments)
        trace(i);
}

The goal is to have a function that I can call and list any given amount of stylesheets within, eg:

$avian->insertStyles("overall.css", "home.css");

*Subject to obvious limitations (RAM, etc).

2
  • Similar question: stackoverflow.com/questions/1577383/… Commented Jun 20, 2011 at 9:16
  • @Bing Cheers - had a quick search before I asked but this didn't come up. Commented Jun 20, 2011 at 9:18

3 Answers 3

7
function multiTrace() 
{
    $args = func_get_args();
    while ($arg = array_shift($args)) {
        echo $arg; 
    }
}

see: http://php.net/manual/en/function.func-get-args.php

Sign up to request clarification or add additional context in comments.

5 Comments

@Peter Kruithof Also just an example, the while loop is a bit problematic. Think of what happens if one of the given parameters is 0 or false (or anything which can be cast to boolean false.)
Marty, you should accept an answer, if it answers your question :) You might also want to look at func_num_args() and func_get_arg(), though func_get_args() seems to be the one that's used in most cases. You might also be interested in default argument values, e.g., function getUerName($userID = null) { }.
@Yoshi, good point. I would use foreach ( $args as $arg ) { }.
@binaryLV @Peter Kruithof Yes, if a loop is need that's what I'd use, too.
@binaryLV There's a minimum time applied to answer acceptance - I know how to use SO. Also, thanks for the additional links.
3

See

http://nl.php.net/manual/en/function.func-get-args.php

function testfunction() {
    $arguments = func_get_args();

    var_dump($arguments);
}

testfunction("argument1", "argument2");

Result:

array
  0 => string 'argument1' (length=9)
  1 => string 'argument2' (length=9)

Comments

1

I think you are after the func_get_args function:
http://php.net/manual/en/function.func-get-args.php

Comments

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.