2013-03-16 57 views
0

我想知道如果有一个PHP“字符串...字符串数组”等同,这东西能根据“字符串数组”参数建立一个数组,即Java“的字符串... someStrings”等同于PHP

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" 
} 

有没有办法用PHP来做同样的事情?

我知道我可以使用

function processStrings($a, $b){} 

,然后调用它像这样

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

但我想知道是否有传递的参数,比如我做一个未定义的数字的方式与Java

+0

你有超过一千的声望。我相信你可以为你的问题想出一个更好的标题。 – 2013-03-16 16:04:21

+0

有一个与你有关的问题,你看到了吗? http://stackoverflow.com/questions/10128477/call-function-with-unknown-variable-number-of-parameters – 2013-03-16 16:11:15

+0

@GökhanÇoban不,我没看到它,但我需要我的功能,要求至少2个参数(可能无需手动检查func_num_args> = 2)... – BackSlash 2013-03-16 16:21:10

回答

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

虽然你可以做到这一点,但我并没有在你的函数中定义任何参数,因为当任何定义的参数被省略时,它会变得非常混乱。

+0

如果需要至少有2个参数,该怎么办?即'function1($ a,$ b [,$ c ...])'我该怎么做(可能不需要手动检查'func_num_args> = 2')? – BackSlash 2013-03-16 16:25:15

+0

您可以定义参数,因为我没有在我的答案中提供。你应该知道func_get_args()将所有的参数作为数组。 – 2013-03-16 16:26:08

+0

在你的使用方式中,php没有确切的等价物。 – 2013-03-16 16:31:35