什么时候在PHP中使用变量变量? [英] When to use a variable variable in PHP?

查看:101
本文介绍了什么时候在PHP中使用变量变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在PHP中开发了一段时间了,但是我还没有执行必须使用变量变量的任务.谁能给我示例使用它们的一个好主意吗?还是只是出于娱乐目的将它们包含在语言中?

I've been developing in PHP for a while now, and I still have not had a task where I've had to use variable variables. Can anyone give me examples where using them is a good idea ? Or were they included in the language just for fun ?

推荐答案

我不得不使用它们的一种情况是URI处理,尽管这种技术可能已经过时了,并且我承认很长一段时间都没有使用它

One situation where I've had to use them is URI processing, although this technique might be dated, and I admittedly haven't used it in a long time.

假设我们要以domain.tld/controller/action/parameter/s格式从脚本中提取URI.我们可以使用以下命令删除脚本名称:

Let's say we want to pull the URI from the script in the format domain.tld/controller/action/parameter/s. We could remove the script name using the following:

$uri_string = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['REQUEST_URI']);

要从中提取控制器,动作和参数值,我们将不得不使用路径定界符"/"来分解字符串.但是,如果我们使用前导或尾部定界符,则爆炸时将具有空数组值,因此我们应从字符串的开头和结尾处修剪这些值:

To extract the controller, action, and parameter values from this we're going to have to explode the string using the path delimiter '/'. However, if we have leading or trailing delimiters, we'll have empty array values upon explosion, so we should trim those from the beginning and end of the string:

$uri_string = trim($uri_string, '/');

我们现在可以将路径分解为数组:

We can now explode the path into an array:

$uri_data = explode('/', $uri_string);

现在,

$uri_data[0]包含我们的控制器名称,$uri_data[1]包含动作名称,并且数组之外的值是应传递给该动作方法的参数.

$uri_data[0] now contains our controller name, $uri_data[1] contains the action name, and values in the array beyond that are parameters that should be passed to the action method.

$controller_name = $uri_data[0];
$action_name = $uri_data[1];

因此,既然我们有了这些名称,我们就可以将它们用于许多事情.如果将控制器放在相对于站点根目录的非常特定的目录中,则可以使用此信息require_once控制器类.此时,您可以实例化它并使用变量变量调用它:

So, now that we have these names, we can use them for a number of things. If you keep your controllers in a very specific directory relative to the site root, you can use this information to require_once the controller class. At that point, you can instantiate it and call it using variable variables:

$controller = new $controller_name();
$controller->{$action_name}();    // Or pass parameters if they exist

这种方法有很多安全隐患值得关注,但这是我见过的利用变量变量的一种方法.

There are a lot of security gotchas to look out for in this approach, but this is one way I've seen to make use of variable variables.

免责声明:我不建议您实际使用此代码.

DISCLAIMER: I'm not suggesting your actually use this code.

这篇关于什么时候在PHP中使用变量变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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