Passing variables to obejct method on Flight PHP

1k Views Asked by At

According to the Flight PHP documentation, to use an object method is by using:

Flight::route('/some/route', [$object, 'method']);

and to use route parameters is by using:

Flight::route('/@name/@id', function($name, $id){
    echo "hello, $name ($id)!";
});

I tried to combine both like this:

Flight::route('/user/@id', [$object, 'method']);

but it doesn't work. Is there any way to pass parameters to an object method?

3

There are 3 best solutions below

0
ishegg On

How about assigning the variables in the closure?

Flight::route('/@name/@id', function($name, $id){
    $obj = new Object; // or use a DIC
    $obj->name = $name;
    $obj->id = $id; // or assign these in the constructor
});
0
Gras Double On

Looking at Dispatcher.php (methods callFunction and invokeMethod), your use case is supposed to be supported. Parameters should be supported equally well in anonymous functions and in class methods...

0
R. Perlinski On

This code works for me:

function someFunction($id) {
  echo 'id: ' . $id;
}

class SomeClass {
    function method1($id) {
      echo 'Class, id: ' . $id;
    }
    function method2($name, $id) {
      echo 'Class, name: ' . $name . ', id: ' . $id;
    }
}
$object = new SomeClass();

Flight::route('/user/@id', array($object, 'method1'));
Flight::route('/user/@id/@name', array($object, 'method2'));
Flight::route('/fun/@id', 'someFunction');

I am not good wit PHP but it's something with callbacks: https://www.exakat.io/the-art-of-php-callback/