2014-02-11 27 views
0

如何將一個PHP數組的所有值傳遞給函數作爲參數? 我試過的範圍()函數,但只返回一個整數:將數組的所有值作爲參數傳遞給一個函數

$obj = new Test(); 
$arr = array("hello", "hi", "hello"); 
foreach(range($arr[0], $arr[sizeof($arr)]) as $args) { 
    call_user_func_array(array($obj, 'func'), $args); 
} 

class Test { 
    public function func() { 
     $args = func_get_args(); 
     echo $args[0]; // I want that to print "hello" 
    } 
} 

// Warning: call_user_func_array() expects parameter 2 to be array, integer given on line 4 
+0

你不需要'foreach'。只需使用:'call_user_func_array(array($ obj,'func'),$ arr);' – hindmost

回答

0
$obj = new Test(); 
$arr = array("hello", "hi", "hello"); 
call_user_func_array(array($obj, 'func'), $arr); 

class Test { 
    public function func() { 
     $args = func_get_args(); 
     echo $args[0]; // I want that to print "hello" 
    } 
} 
0

爲什麼不通過,則該數組處理它在你的func()方法。例如

$arr = array('hello','goodbye'); 

$test = new Test; 
$test->func($arr); 

class Test { 
    public function func($args) { 
     echo $args[0]; // I want that to print "hello" 
    } 
} 
0
$obj = new Test(); 
$arr = array("hello", "hi", "hello"); 
$obj ->func($arr); 
class Test 
{ 
    public function func($arr) 
    { 
     foreach ($arr as $key => $value) 
     { 
     echo $value."</br>";// Output all the values in array 
     } 
    echo $arr[0];//To print first value of array 
    } 
} 
相關問題