【问题标题】:Passing variables to obejct method on Flight PHP将变量传递给Flight PHP上的对象方法
【发布时间】:2018-01-26 01:40:39
【问题描述】:

根据Flight PHP documentation,使用对象方法是通过使用:

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

并且使用路由参数是通过使用:

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

我尝试像这样将两者结合起来:

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

但它不起作用。有没有办法给对象方法传参数?

【问题讨论】:

    标签: php rest flightphp


    【解决方案1】:

    如何在闭包中分配变量?

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

    【讨论】:

      【解决方案2】:

      查看Dispatcher.php(方法callFunctioninvokeMethod),应该支持您的用例。匿名函数和类方法中的参数应该同样得到很好的支持...

      【讨论】:

        【解决方案3】:

        此代码适用于我:

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

        我不擅长 PHP,但它与回调有关: https://www.exakat.io/the-art-of-php-callback/

        【讨论】:

          猜你喜欢
          • 2016-04-02
          • 2012-07-12
          • 1970-01-01
          • 2013-10-12
          • 2016-04-20
          • 2016-01-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多