带有引用的 call_user_func_array [英] call_user_func_array with references
问题描述
我基本上是在尝试调用 mysqli::bind_param 通过 call_user_func_array
.
I'm basically trying to call mysqli::bind_param via call_user_func_array
.
这是我的功能:
function Insert($table, $values=array(), $flags=0) {
$field_count = count($values);
if($field_count > 0) {
$fields = implode(',',array_keys($values));
$placeholders = implode(',',array_repeat('?',$field_count));
} else {
$fields = '';
$placeholders = '';
}
if($flags > 0) {
$flag_arr = array();
if($flags & self::LOW_PRIORITY) $flag_arr[] = 'LOW_PRIORITY';
if($flags & self::DELAYED) $flag_arr[] = 'DELAYED';
if($flags & self::HIGH_PRIORITY) $flag_arr[] = 'HIGH_PRIORITY';
if($flags & self::IGNORE) $flag_arr[] = 'IGNORE';
$flags_str = implode(' ',$flag_arr);
} else {
$flags_str = '';
}
$sql = "INSERT $flags_str INTO $table ($fields) VALUES ($placeholders)";
$stmt = $this->mysqli->prepare($sql);
if($stmt === false) {
throw new Exception('Error preparing MySQL statement.<br/>MSG: '.$this->mysqli->error.'<br/>SQL: '.$sql);
}
if($field_count > 0) {
$types = '';
foreach($values as $val) {
if(is_int($val)) $types .= 'i';
elseif(is_float($val)) $types .= 'd';
elseif(is_string($val)) $types .= 's';
else $types .= 'b';
}
$params = array_merge(array($types),array_values($values));
call_user_func_array(array($stmt,'bind_param'),$params);
}
$stmt->execute();
return $stmt;
}
问题发生在 call_user_func_array
行上.我收到此错误:
The problem occurs on the call_user_func_array
line. I get this error:
mysqli_stmt::bind_param() 的参数 2 应为引用,给定值
Parameter 2 to mysqli_stmt::bind_param() expected to be a reference, value given
我明白这个问题,只是不知道如何解决.
I understand the problem, I'm just not sure how to work around it.
举个例子,函数可以这样调用:
As an example, the function may be called like this:
$db->Insert('pictures',array('views'=>1));
并且 var_dump($params)
会产生这个:
array
0 => string 'i' (length=1)
1 => int 1
那么,有没有办法用可变数量的参数调用mysqli::bind_param
,或者以某种方式使我的数组成为引用?
So, is there a way to call mysqli::bind_param
with a variable number of arguments, or somehow make my array into references?
推荐答案
将 mysqli_stmt_bind_param() 与 call_user_func_array() 结合使用时必须小心.请注意,mysqli_stmt_bind_param() 需要通过引用传递参数,而 call_user_func_array() 可以接受可以表示引用或值的变量列表作为参数.
Care must be taken when using mysqli_stmt_bind_param() in conjunction with call_user_func_array(). Note that mysqli_stmt_bind_param() requires parameters to be passed by reference, whereas call_user_func_array() can accept as a parameter a list of variables that can represent references or values.
有一个解决方案 发布在手册的用户评论部分.简而言之,您创建了一个函数,该函数接受一个数组并返回一个重复数组,该数组的元素是对源数组中元素的引用.
There is a solution posted in the user-comments section in the manual. In short, you make a function that accepts an array and returns a duplicate array whose elements are references to the elements in the source array.
这篇关于带有引用的 call_user_func_array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!