PHP中的变量变量-它们的目的是什么? [英] Variable variables in PHP - What is their purpose?

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

问题描述

在PHP中,有一个正式称为"变量变量的功能,其中一个可以分配变量的变量.变量变量将一个变量的值用作新变量的名称!例如:

In PHP there's a functionality officially called "Variable Variables" where one can assign variable variables. A variable variable takes the value of one variable as the name for a new variable! For example:

$name='Joe';
$$name='Smith'; // could also be written as ${$name}='Smith'

第一个变量$ name包含值'Joe',第二个变量名为$ Joe变量,值为'Smith'.考虑到PHP变量区分大小写!

The first variable $name contains the value 'Joe', while the second is variable named $Joe with the value 'Smith'. Take into account that PHP variables are case-sensitive!

我从没使用过此功能,也没有看到它的目的.有人可以向我解释在哪里可以很好地利用此功能吗?

I've never used this functionality and do not see the purpose for that. Could someone explain to me where this functionality could be exploited as a good practise?

推荐答案

有时我们需要非常灵活且可以参数化的软件.当然,您必须准备全部内容,但是其中一部分只是来自用户输入,我们没有时间更改软件,只是因为用户需要新输入.

Sometimes we need software that is extremely flexible and that we can parametrize. You have to prepare the whole thing, of course, but part of it just comes from user input, and we have no time to change the software just because the user needs a new input.

有了可变变量和可变函数,您可以解决没有它们就很难解决的问题.

With variable variables and variable functions you can solve problems that would be much harder to solve without them.

$comment = new stdClass(); // Create an object

$comment->name = sanitize_value($array['name']);
$comment->email = sanitize_values($array['email']);
$comment->url = sanitize_values($array['url']);
$comment->comment_text = sanitize_values($array['comment_text']);

具有可变变量

$comment = new stdClass(); // Create a new object


foreach( $array as $key=>$val )
{
    $comment->$key = sanitize_values($val);
}

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

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