Когда использовать переменную переменную в PHP?

Это должно быть

sort -k 4n out1.txt

Только что проверил это с помощью сортировки GNU (--debug enabled):

$ tac input | /bin/sort --debug -k 4n
/bin/sort: using simple byte comparison
/bin/sort: key 1 is numeric and spans multiple fields
AX-18 Chr1_419085 1 41908545 T C -1 98 0.51
                    ________
___________________________________________
AX-19 Chr1_419087 1 41908740 T C 0 15 0.067
                    ________
___________________________________________
AX-20 Chr1_419087 1 41908741 T C 0 13 0.067
                    ________
___________________________________________
5
задан Charles 25 December 2012 в 02:05
поделиться

7 ответов

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.

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] 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];

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.

5
ответ дан 18 December 2019 в 05:36
поделиться

Обычно я нахожу их там, где код плохо пахнет. Может быть, ссылается на статическую переменную конфигурации и т.д. Но почему бы лучше не использовать обычный ассоциативный массив. Похоже, дыра в безопасности ждет своего часа.

Я полагаю, вы могли бы эффективно использовать их в шаблонах.

9
ответ дан 18 December 2019 в 05:36
поделиться

Это не редкость, когда языки включают функции, которые нельзя трогать удочкой (я даже задал вопрос об этом некоторое время назад), и переменные переменные, вероятно, одна из тех конструкций, которые попадают в эту категорию. Тот факт, что язык содержит функцию, не означает, что вы должны ее использовать.

Могут быть случаи, когда они решают проблему (в конце концов, рекурсия редко используется на практике, но никто не будет спорить, что это несущественно construct), но в целом к ​​любой языковой функции, которая скрывает то, что делает ваш код, а переменные переменные явно попадают в эту категорию, следует относиться с особой осторожностью.

2
ответ дан 18 December 2019 в 05:36
поделиться

Never use them; an "array" is always a better solution.

7
ответ дан 18 December 2019 в 05:36
поделиться

First off, it'd be a huge security concern were you to use user output for these purposes. Internals are the only valid use here.

Given that, I imagine it's for things like looping through various variables, or sending variables as parameters.

foreach($name in array('_GET','_POST','_REQUEST')) {
    array_map('stripslashes',$$name);
}
6
ответ дан 18 December 2019 в 05:36
поделиться

Unless you are working with multi-depth variables (which you won't need to if you are not doing anything fancy) you will probably don't need them. Even then, you can probably find another way to write down the same thing and still get the same result. It can be shorter (and in some cases even easier to understand) to use them though, so I for one am glad that it is part of the language.

0
ответ дан 18 December 2019 в 05:36
поделиться

Я не нашел много применений для переменных переменных, но использование переменных для методов может быть удобно, если вам ясно, что вы делаете. Например, в простой службе REST вы можете сделать что-то вроде этого:

0
ответ дан 18 December 2019 в 05:36
поделиться
Другие вопросы по тегам:

Похожие вопросы: