Variable variables in PHP - What is their purpose?(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 中的变量 - 它们的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP 中的变量 - 它们的目的是什么?


- 从 PHP 中的输入表单获取日期 2022-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- Laravel 仓库 2022-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01