发布于 2015-08-09 09:52:32 | 348 次阅读 | 评论: 0 | 来源: 网络整理
在swoole_server/swoole_client的事件回调函数中,需要读取调用外部的变量和对象,可以通过下面的几种方法实现。
class Server
{
public $buffer;
public $serv;
function onReceive($serv, $fd, $from_id, $data)
{
//在这里可以读取到EventCallback对象上的属性和方法
$this->buffer[$fd] = $data;
$this->hello();
}
function hello()
{
}
function run()
{
$serv = new swoole_server('127.0.0.1', 9501);
$this->serv = $serv;
$serv->on('receive', array($this, 'onReceive'));
$serv->start();
}
}
$server= new Server;
$server->run();
$buffer = array();
$serv->on('receive', function($serv, $fd, $from_id, $data) {
global $buffer;
$buffer[$fd] = $data;
});
class Test
{
static $buffer;
}
$serv->on('receive', function($serv, $fd, $from_id, $data) {
Test::$buffer[$fd] = $data;
});
$buffer = array();
$serv->on('receive', function($serv, $fd, $from_id, $data) use ($buffer) {
$buffer[$fd] = $data;
});
需要PHP5.4或更高的版本
多个参数可以用逗号隔开,如use ($buffer, $users, $config)
$serv->buffer = array();
$serv->on('receive', function($serv, $fd, $from_id, $data) use ($buffer) {
$serv->buffer[$fd] = $data;
});