0

i was wondering if there is a "String...stringArray" equivalent in PHP, something that can build an array based on "stringArray" parameters, i.e.

Java:

public void method1(){
    int aNumber = 4;
    String string1 = "first string";
    String string2 = "second string";
    String string3 = "third string";

    processStrings(aNumber, string1, string2, string3);
    /*
       string1, string2 and string3 will become b = {string1, string2, string3}
       in function "processStrings"
    */
}

public void processStrings(int a, String...b){
    System.out.println(b[0]); //in this case it will print out "first string"
    System.out.println(b[1]); //in this case it will print out "second string"
    System.out.println(b[2]); //in this case it will print out "third string"
}

Is there a way to do the same thing with PHP?

I know i can use

function processStrings($a, $b){}

and then call it like this

function method1(){
    $myInt = 4;
    $strings = array("first string","second string","third string");
    processStrings($myInt, $strings);
}

But i would like to know if there is a way to pass an undefined number of parameters like i do with Java

4

1 回答 1

0

来自 php 手册:func_get_args()

<?php
function foo()
{
    $numargs = func_num_args();
    echo "Number of arguments: $numargs<br />\n";
    if ($numargs >= 2) {
        echo "Second argument is: " . func_get_arg(1) . "<br />\n";
    }
    $arg_list = func_get_args();
    for ($i = 0; $i < $numargs; $i++) {
        echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
    }
}

foo(1, 2, 3);
?>

虽然你可以做到,但我建议不要在你的函数中定义任何参数,因为当任何已定义的参数被省略时,它会变得非常混乱。

于 2013-03-16T16:17:52.233 回答