执行redis命令的时候报了一堆错误。。不明白是什么原因。。

dayayz

RT,源码大体是这样,

   $redis = new Redis();
   $redis->connect('127.0.0.1', 6379);
  if($redis) {echo "Connection to server sucessfully\n";}
   //check whether server is running or not
   echo "Server is running: ".$redis->ping()."\n";
   echo $redis->get("data1")."\n"; 

$task1 = new Worker();
$task1->name = 'device1';
$task1->onWorkerStart = function($task)
{
    $time_interval = 3;
    Timer::add($time_interval, function()
    {
    echo $redis->get("data1"); 
     });
};

CMD里提示的内容是这样,

G:\workerman-for-win-master\workerman-for-win-master>php Applications\example\device1.php
Connection to server sucessfully
Server is running: +PONG
1000
----------------------- WORKERMAN -----------------------------
Workerman version:3.2.5          PHP version:7.0.3
------------------------ WORKERS -------------------------------
worker        listen        processes status
device1       none           1        
-----------------------------------------------------------------------
Press Ctrl-C to quit. Start success.
PHP Notice:  Undefined variable: redis in G:\workerman-for-win-master\workerman-for-win-master\Applications\example\device1.php on line 27

Notice: Undefined variable: redis in G:\workerman-for-win-master\workerman-for-win-master\Applications\example\device1.php on line 27
PHP Fatal error:  Uncaught Error: Call to a member function get() on unknown in G:\workerman-for-win-master\workerman-for-win-master\Applications\example\device1.php:27
Stack trace:
#0 : {closure}()
#1 G:\workerman-for-win-master\workerman-for-win-master\Events\Select.php(187): call_user_func_array(Object(Closure), Array)
#2 G:\workerman-for-win-master\workerman-for-win-master\Events\Select.php(226): Workerman\Events\Select->tick()
#3 G:\workerman-for-win-master\workerman-for-win-master\Worker.php(740): Workerman\Events\Select->loop()
#4 G:\workerman-for-win-master\workerman-for-win-master\Worker.php(428): Workerman\Worker->run()
#5 G:\workerman-for-win-master\workerman-for-win-master\Worker.php(345): Workerman\Worker::runAllWorkers()
#6 G:\workerman-for-win-master\workerman-for-win-master\Applications\example\device1.php(32): Workerman\Worker::runAll()
#7 {main}
  thrown in G:\workerman-for-win-master\workerman-for-win-master\Applications\example\device1.php on line 27

查了一下相关的问题,感觉也不像CLI类加载失败的情况,毕竟在Worker上面的内容都正常,连接redis也正常,到了worker的timer里就出问题了。。
求解答。。。

阅读 3337
1个回答

walkor

定时器内的$redis变量是函数外部定义的变量,函数内部无法直接使用。需要global关键字引用。这个是php基础知识哦。

另外workerman不允许在主进程初始化资源(这个手册有明确说明哦),可以把new redis放到onWorkerStart中去。

  • dayayz 2016-04-05

    。。。感谢大大的回复。。
    global也能引用外部对象的方法吗?。。我试着在timer里面加上global了,还是提示错误。。

  • dayayz 2016-04-05

    @931:感谢大大。。自行解决了。。。加了use($redis)就好了、。。。谢谢!