简体   繁体   中英

How to pass global variable to Gearman worker (PHP)

My Gearman workers need to connect to my database. How can I pass a reference to my global $db variable? In the code below, $db is undefined in the executeJob function.

$db = new mysqli($db_host, $db_user, $db_pass, $db_name, $db_port);

// set up Gearman worker
$worker = new GearmanWorker();
$worker->addServer();
$worker->addFunction("execute", "executeJob");
while($worker->work());

function executeJob($job) {
    global $db;
    print_r($db); \\ UNDEFINED
}

The php manual suggests that context data can be passed when setting up the worker function with addFunction , but it's not clear to me if that's what I need or even how to do it. Thanks!!

Yes, context data is what you need.

$db = new mysqli($db_host, $db_user, $db_pass, $db_name, $db_port);

// set up Gearman worker
$worker = new GearmanWorker();
$worker->addServer();
$worker->addFunction("execute", "executeJob", $db);
while($worker->work());

function executeJob($job, $db) {
    print_r($db);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM