Skip to content
Advertisement

How can I add a parameter to a callback function like in JavaScript?

I wanted to make a small function that let’s me connect to the database, do something in a callback function and then automatically close the connection like so:

function mysqli_conn( $connection( $mysqli ) ) {
    $connection( new mysqli($c_host, $c_user, $c_password, $c_database ) );
    $mysqli->close();
}

Usage would be like this:

mysqli_conn(function( $mysqli ) {
    $sql = "INSERT INTO some_table (info1, info2, info3, info4) VALUES (?, ?, ?, ?)";
    $stmt = $mysqli->prepare($sql);
    $stmt->bind_param("ssss", $info1, $info2, $info3, $info4);
    $stmt->execute();
    $stmt->close();     
});

Is it possible to achieve this somehow? Because my mysqli_conn doesn’t seem to work.

How to do it?

Advertisement

Answer

Supposing the $c_... are globals / defined in the same file:

function mysqli_conn( $connection ) {
    $mysqli = new mysqli($c_host, $c_user, $c_password, $c_database );
    $connection( $mysqli );
    $mysqli->close();
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement