我在这个领域还比较新,所以请耐心点。我有一门课里面没有什么功能。它使用工人启动服务器。我试图在服务器引导(function load())上加载一些数据,然后在请求$key时使用这些数据在页面上显示。类似于API调用。
csv中的数据是
doctor,31234-32223
police officer,342-341
firefighter,543-3345
worker,12223
developer,120045class App
{
public $getPair = null;
public $dataToLoad= [];
protected $dispatcher = null;
/**
* start
*/
public function start()
{
$this->dispatcher = \FastRoute\simpleDispatcher(function(\FastRoute\RouteCollector $r) {
foreach ($this->routeInfo as $method => $callbacks) {
foreach ($callbacks as $info) {
$r->addRoute($method, $info[0], $info[1]);
}
}
});
\Workerman\Worker::runAll();
}
function load()
{
$files = "load.csv";
foreach($files as $file) {
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 4096, ",")) !== FALSE) {
$dataToLoad[$data[1]] = $data[0];
}
fclose($handle);
}
}
return $this->dataToLoad;
}
function getData($getPair) {
foreach ($this->dataToLoad as $key => $value){
if($getPair === $key){
return array($key.','.$value);
} else {
echo "missing";
}
}
}
/**
* @param TcpConnection $connection
* @param Request $request
* @return null
*/
public function onMessage($connection, $request)
{
static $callbacks = [];
try {
$path = $request->path();
$method = $request->method();
$key = $method . $path;
$callback = $callbacks[$key] ?? null;
if ($callback) {
$connection->send($callback($request));
return null;
}
$ret = $this->dispatcher->dispatch($method, $path);
if ($ret[0] === Dispatcher::FOUND) {
$callback = $ret[1];
if (!empty($ret[2])) {
$args = array_values($ret[2]);
$callback = function ($request) use ($args, $callback) {
return $callback($request, ... $args);
};
}
$callbacks[$key] = $callback;
$connection->send($callback($request));
return true;
} else {
$connection->send(new Response(404, [], '<h1>404 Not Found</h1>'));
}
} catch (\Throwable $e) {
$connection->send(new Response(500, [], (string)$e));
}
}然后我就有了index.php和下面的
use Mark\App;
$api = new App('http://0.0.0.0:3000');
$api->count = 4; // process count
$api->load(); //load data
$api->get('/key/{key}', function ($request, $key) {
return $api->getData("doctor");
});
$api->start();错误出现在index.php文件的return $api->getData("key");行中。
错误:调用null PHP上的成员函数getData()警告:未定义变量$api
为什么在这种情况下getData()是空的,为什么没有定义,因为当我在上面的new App()...上分配它时,我已经初始化了它?
ps。服务器已正确启动,且没有错误。
发布于 2022-11-13 19:55:01
匿名/闭包函数没有作用域给$api,因此可以通过use传递。
$api->get('/key/{key}', function ($request, $key) use ($api) {
return $api->getData("doctor");
});附带注意:getData函数缺少public。
https://stackoverflow.com/questions/74424174
复制相似问题