PHP 中的变量 - 它们的目的是什么?

2021-12-22 00:00:00 data-structures variables syntax 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);
}

相关文章