将数组传递给函数参数
问题描述:
可以在函数参数中传递数组吗?例如,将数组传递给函数参数
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)
}
剧本是从我修改了一个笨的插件,所以我想不杀猪太多。
答
将数组传递给函数绝对没问题。许多PHP自带的array_*()
函数接收数组参数,然后返回数组。
至于从函数返回数组 - 这是从单个函数返回多个值的极好方法。
+0
哦,我明白了!thx。我可以返回'$ data'吗?而不是每个值? – CyberJunkie 2011-05-25 02:40:39
答
可以在函数参数中传递数组吗? =>是的!
答
如果您需要返回多个值,则数组是一种方法。
您也可以返回一个对象,只是实例化stdClass
并设置属性。
答
可以通过array
作为参数,也可以返回array
作为结果。在PHP
我们一直这样做。
也可以传递和返回其他语言的数组......如Python
他们经常这样做,例如, process_parameters(*parameters)
。
如果你传递一个对象,它甚至是可以的!或返回一个对象......像这样:
$dbConnection = get_db_connection('mysql'); // $dbConnection is an instance of MySQLDbConnection now
为什么不....... – Dani 2011-05-25 02:42:08
,因为我还没有完全理解它:( – CyberJunkie 2011-05-25 02:45:39
当你所有的代码工作,你想要的方式?现在,在返回数组中有一些奇怪的花括号('并且可能在'if($ activated)'之后缺少'{'),我开始执行这个操作。编辑自己,但意图是不清楚在哪里缺少'{'是。 – 2011-05-25 02:59:21