如何将全局变量传递给 Gearman worker (PHP)

How to pass global variable to Gearman worker (PHP)

我的 Gearman worker 需要连接到我的数据库。如何传递对全局 $db 变量的引用?在下面的代码中,$dbexecuteJob 函数中未定义。

$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
}

php 手册建议在使用 addFunction 设置辅助函数时可以传递上下文数据,但我不清楚这是否是我需要的,甚至不清楚如何去做。谢谢!!

是的,上下文数据就是您所需要的。

$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);
}