如何解决PHP 访问变量数组作为分隔变量
我遇到了一个有趣的问题。
我不能将像 $variables = [$var1,$var2,$var3];
这样的变量数组分配给一个函数并像 my_function($var1,$var3);
一样单独使用它们,所以我可以拥有 my_function($variables)
这可能吗?请注意,my_function
不会接受数组。
在我的代码中:
所以当我运行这个时:
$query = "SELECT * FROM books as b where b.id=?";
$result = Query::select($query,'i',1);
或者当我运行这个时:
$query = "SELECT * FROM books as b where b.id=? b.name=?";
$name = 'Sam';
$result = Query::select($query,'is',1,$name);
这个方法会执行:
public static function select($query,$string_of_types,...$variables)
{
$MysqL = new MysqLi(DB::$servername,DB::$username,DB::$password,DB::$databasename);
$stmt = $MysqL->prepare($query);
///////start mess up//////
if(count($variables) == 1)
$stmt->bind_param($string_of_types,$variables[0]);
if(count($variables) == 2)
$stmt->bind_param($string_of_types,$variables[0],$variables[1]);
if(count($variables) == 3)
$stmt->bind_param($string_of_types,$variables[1],$variables[2]);
$stmt->execute();
$result = $stmt->get_result();
return $result;
}
它正在起作用,但我知道我走错了路。
我该如何解决这个问题?
如果我以某种方式神奇地移除 []
周围的 $variables
,那么一切都会正常进行。所以我可以写$stmt->bind_param($string_of_types,$variables);
解决方法
您要查找的是 splat 运算符 (...
),它将数组解包到函数参数列表中:
$stmt->bind_param($string_of_types,...$variables);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。