0

I am having some trouble regarding PHP NATS. I am getting and printing msg body values. Everything is working fine. Just returning result is the problem. Here is the code

function connect(){
    require_once __DIR__ . "/../../vendor/autoload.php";
    $connectionOptions = new \Nats\ConnectionOptions();
    $connectionOptions->setHost('localhost')->setPort(4222);
    $c = new Nats\Connection($connectionOptions);
    $c->connect();
    $c->request('sayhello', 'Marty McFly', function ($response) {
      echo $response->getBody();    
      return $response->getBody();
    });
}

echo is working and printing values, while return isn't returning anything if I use like this.

$res = connect():
print_r($res);
h_h
  • 1,201
  • 4
  • 28
  • 47
  • 1
    You are returning data from within a callback function here, but that return value will only disappear into thin air, if the method that called the callback doesn’t do anything with that return value itself. Looking at the code of the PHP client on GitHub, I think that whole thing is meant to be used in some sort of asynchronous way(?), which means returning stuff out of the callback function would be the wrong approach to begin with; the result is likely supposed to be handled _inside_ that callback function in such a scenario. – 04FS Feb 05 '19 at 11:27
  • Is there any possibility, we can get result outside? – h_h Feb 05 '19 at 11:46

1 Answers1

1

You are echoing from the scope of the anonymous function, and returning from the scope of connect() function.

One approach you can take is callback, you can make your function to take a Closure as an argument and run it from within connect() with the result as an argument:

function connect(\Closure $callback){
    require_once __DIR__ . "/../../vendor/autoload.php";
    $connectionOptions = new \Nats\ConnectionOptions();
    $connectionOptions->setHost('localhost')->setPort(4222);
    $c = new Nats\Connection($connectionOptions);
    $c->connect();
    $c->request('sayhello', 'Marty McFly', function ($response) use ($callback) {
      echo $response->getBody();    
      $callback(response->getBody());
    });
}

And you would use it as follows:

connect(function ($result) {
    // here you've got an access to the $response->getBody() from connect function

});
matiit
  • 7,969
  • 5
  • 41
  • 65