Fat-Free-Framework全局变量和函数 [英] Fat-Free-Framework global variables and functions

查看:368
本文介绍了Fat-Free-Framework全局变量和函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的无脂框架,我对全局变量有点困惑。

I'm new to fat free framework and i'm a little bit confused about the global variables.

$f3->route('GET /@page','display');

    function display($f3) {
        echo 'I cannot object to an object' . $f3->get('PARAMS.page');
    };

$f3->run();




这里我使用GET / @页面作为网址路线。在
函数中,我使用$ f3-> get('PARAMS.page')来获得该
变量的值。

Here i'm using GET /@page as a token for the url route. In the function i then use $f3->get('PARAMS.page') to get the value of that variable.

从$ f3-> get是获取全局变量的方法,为什么我有
将$ f3类传递给该函数。

Since $f3->get is the method to get a global variable, why do i have to pass the $f3 class to the function.

下面的代码不起作用($ f3没有传递给函数)。

The below code doesn't work ($f3 class not passed to the function).

$f3->route('GET /@page','display');

    function display() {
        echo 'I cannot object to an object' . $f3->get('PARAMS.page');
    };

$f3->run();

所以我的问题是:为什么我必须将$ f3类传递给函数?

So my question is: why do i have to pass the $f3 class to the function?

Thx ...

推荐答案

无论如何,为了方便起见,在路由时将这个F3实例以及路由参数传递给路由处理程序。因此,不要将路由处理程序定义为:

Anyway, for convenience purpose, at routing time this F3 instance as well as the route parameters are passed to the route handler. Therefore, instead of defining your route handler as:

function display() {
    $f3=Base::instance();
    echo 'I cannot object to an object' . $f3->get('PARAMS.page');
};

您可以将其定义为:

you could define it as:

function display($f3) {
    echo 'I cannot object to an object' . $f3->get('PARAMS.page');
};

甚至更好:

or even better:

function display($f3,$params) {
    echo 'I cannot object to an object' . $params['page'];
};

这三个函数是完全相同的,所以你应该选择一个你最了解的函数。但是你应该记住 $ f3 $ params 只在路由时传递 ,这意味着3个函数:路由处理程序,beforeRoute()钩子和afterRoute()钩子。在代码中的任何其他地方(包括类构造函数内部),您应该调用 Base :: instance()来检索F3实例。

These 3 functions are absolutely identical so you should pick up the one that you understand best. But you should remember that $f3 and $params are only passed at routing time, which means to 3 functions: the route handler, the beforeRoute() hook and the afterRoute() hook. Anywhere else in the code (including inside a class constructor), you should call Base::instance() to retrieve the F3 instance.

PS:您的问题是为什么我必须将$ f3类传递给函数?,我建议您重命名它的标题以反映它。

PS: your question being "why do i have to pass the $f3 class to the function?", I would suggest you to rename its title to reflect it.

UPDATE :从版本3.2.1开始,F3实例也被传递给路由处理器类的构造函数:

UPDATE: Since release 3.2.1, the F3 instance is also passed to the constructor of the route handler class:

class myClass {
    function display($f3,$params) {
        echo 'I cannot object to an object' . $params['page'];
    }
    function __construct($f3) {
        //do something with $f3
    }
}

这篇关于Fat-Free-Framework全局变量和函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆