PHP 将变量数组作为分隔变量进行访问

标签 php arrays variables prepared-statement

我尝试编写一个类和方法来通过准备好的语句选择行。

我陷入了一个有趣的问题。

我无法分配像 $variables = [$var1, $var2, $var3]; 这样的变量数组到一个函数并单独使用它们,如 my_function($var1, $var2, $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[0], $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);

关于PHP 将变量数组作为分隔变量进行访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66837988/

相关文章:

php - ImageMagick unicode 字体在 Linux 上安装不起作用

PHP:php "see"对象属性如何?

php - 缓慢的 HTTP/1.1 响应,file_get_contents 远程服务器

在c中使用malloc创建数组

php - 将base64编码的图像保存到PHP中的文件中

c# - 将 JSON 字符串数组转换为 C# 列表对象,为列表中模型的每个字段返回 "null"值

php - jqplot - 使用 php 数组中的值

javascript - 如何在javascript中访问函数外部的变量?

Python递归函数问题

Javascript 设置 window.name - IE 中的问题