2011-05-25 270 views
2

可以在函數參數中傳遞數組嗎?例如,將數組傳遞給函數參數

function something() 
{ 
if ($this->db->insert($this->table_name, $data)) { 
$data = array(
    'user_id' => $this->db->insert_id(); 
    'first_name' => $this->form_validation->set_value('first_name'), 
    'last_name' => $this->form_validation->set_value('last_name'), 
    ); 


if ($activated) 
      $this->create_profile($data); 
      return array(//not sure why i'm returning this 
         'user_id' => $user_id, 
         'first_name' => $first_name, 
         'last_name' => $last_name, 
    }     ); 
    return NULL; 
    } 

,然後傳遞到

private function create_profile($data) 
    { 
    return $this->db->insert($this->profile_table_name, $data) 
    } 

劇本是從我修改了一個笨的插件,所以我想不殺豬太多。

+1

爲什麼不....... – Dani 2011-05-25 02:42:08

+0

,因爲我還沒有完全理解它:( – CyberJunkie 2011-05-25 02:45:39

+0

當你所有的代碼工作,你想要的方式?現在,在返回數組中有一些奇怪的花括號('並且可能在'if($ activated)'之後缺少'{'),我開始執行這個操作。編輯自己,但意圖是不清楚在哪裏缺少'{'是。 – 2011-05-25 02:59:21

回答

2

將數組傳遞給函數絕對沒問題。許多PHP自帶的array_*()函數接收數組參數,然後返回數組。

至於從函數返回數組 - 這是從單個函數返回多個值的極好方法。

+0

哦,我明白了!thx。我可以返回'$ data'嗎?而不是每個值? – CyberJunkie 2011-05-25 02:40:39

1

可以在函數參數中傳遞數組嗎? =>是的!

1

如果您需要返回多個值,則數組是一種方法。

您也可以返回一個對象,只是實例化stdClass並設置屬性。

1

可以通過array作爲參數,也可以返回array作爲結果。在PHP我們一直這樣做。

也可以傳遞和返回其他語言的數組......如Python他們經常這樣做,例如, process_parameters(*parameters)

如果你傳遞一個對象,它甚至是可以的!或返回一個對象......像這樣:

$dbConnection = get_db_connection('mysql'); // $dbConnection is an instance of MySQLDbConnection now