Home > OS >  Function always return null when call it
Function always return null when call it

Time:11-14

I'm relatively new in the field so please bear with me. I have a class with few function inside. It uses workerman to start an server. I'm trying to load some data on server boot (function load()) and then using that data to display on the page when ask for some $key. Something like API calls.

Data in the csv is

doctor,31234-32223
police officer,342-341
firefighter,543-3345
worker,12223
developer,120045
class 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));
        }
    }

Then I have index.php with following

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();

The error is in the index.php file on the line return $api->getData("key");

Error: Call to a member function getData() on null

PHP Warning: Undefined variable $api

Why getData() is null in this case and why is undefined since I have initialized it when I assign it on new App()... above?

ps. The server is started correctly and without errors.

CodePudding user response:

The anonymous/closure function does not have scope to $api, so this can be passed with use.

$api->get('/key/{key}', function ($request, $key) use ($api) {
    return $api->getData("doctor");
});

Side note: the getData function is missing public.

  •  Tags:  
  • php
  • Related