問題描述
在 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 中的變量 - 它們的目的是什么?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!