user1983793 user1983793 - 1 month ago 15
PHP Question

pass function with argument to method call

I'm trying to use flight PHP framework for routing and medoo framework for database usage.

//connect database
$database = new medoo([
'database_type' => 'sqlite',
'database_file' => 'db.sqlite'
]);
//my function
function database($database){
$database->insert("ppl", [
"fn" => "joe","ln"=>"doe"]);

}
//
Flight::route('/add/', array(database($database)));


How to invoke my function with argument from this place:

Flight::route('/add/','database')


Tried different variants but getting errors.

Answer

I don't know medoo or flight, but you might be able to use an anonymous function with use:

Flight::route('/add/',
              function() use($database) {
                  $database->insert("ppl", ["fn"=>"joe","ln"=>"doe"])
              });

I think you need to re-architect this into an OOP style that will make it much easier and modular, but in a crunch if $database is defined in the global scope:

function database() {
    $GLOBALS['database']->insert("ppl", ["fn"=>"joe","ln"=>"doe"]);
}

Flight::route('/add/', 'database');
Comments