WorkerMan中无法使用启动时定义的变量

iz

问题描述

我在开发ioBlog,已经开发了一个骨架,但测试时发现onWorkerStart初始化后的变量$db在Worker回调(onMessgae)内完全无法使用。
有办法让启动时初始的变量在Worker内使用吗?

程序代码

$worker->onWorkerStart = function(){
        include(_lib.'/theme.php');
        include(_lib.'/url.php');
        theme::init();
        $db = new Rounger(theme::parse(glob(_etc.'/posts/*.md')));
    };
    $worker->onMessage = function(TcpConnection $con, Request $req){
        if(!$db->exists($req->uri())) $con->send(new Response(404, [], '<h1>404</h1>'));
        else                          $con->send(new Response(200, [], $db->get($req->uri())));
    };

报错信息

PHP Warning:  Undefined variable $db in D:\my\Documents\ioblog\lib\autorun.php on line 25
Error: Call to a member function exists() on null in D:\my\Documents\ioblog\lib\autorun.php:25
Stack trace:
#0 D:\my\Documents\ioblog\vendor\workerman\workerman\Connection\TcpConnection.php(646): {closure}()
#1 D:\my\Documents\ioblog\vendor\workerman\workerman\Events\Select.php(311): Workerman\Connection\TcpConnection->baseRead()
#2 D:\my\Documents\ioblog\vendor\workerman\workerman\Worker.php(2467): Workerman\Events\Select->loop()
#3 D:\my\Documents\ioblog\vendor\workerman\workerman\Worker.php(1453): Workerman\Worker->run()
#4 D:\my\Documents\ioblog\vendor\workerman\workerman\Worker.php(1396): Workerman\Worker::forkWorkersForWindows()
#5 D:\my\Documents\ioblog\vendor\workerman\workerman\Worker.php(560): Workerman\Worker::forkWorkers()
......
671 1 0
1个回答

2548a

并不奇怪,它们的作用域就不在一起,不定义全局能用才怪了.

  • 暂无评论
年代过于久远,无法发表回答
×
🔝