简体   繁体   English

PHP变量变量名

[英]PHP variable variable name

I need to use dynamic variable names to create an article template: 我需要使用动态变量名称来创建文章模板:

 $templatesAr = array("intro","paragraphs","image","conclusion","h2");
 $intro = "Intro";
 $paragraphs = "Paragraphs";
 $image = "image.png";
 $conclusion = "Conclusion";
 $h2 = "Heading";

$articletemplateAr = array("h2", "intro", "image",
    "h2", "paragraphs", "h2", "conclusion");`

How to echo $article in order from $articletemplateAr: 如何从$ articletemplateAr依次回显$ article:

$article = $h2 . $intro . $image . $h2 . $paragraphs . $h2 . $conclusion;

Use this code: 使用此代码:

$article = '';
foreach($articletemplateAr as $item) {
    $article .= $$item;
}

PHP variable variables are documented here . PHP变量在此处记录 You can use ${$articletemplateAr[$i]} to access the variable whose name is in the array element. 您可以使用${$articletemplateAr[$i]}访问名称在数组元素中的变量。

However, almost any time you find yourself wanting variable variables, a better approach is to use an associative array. 但是,几乎在任何时候您想要变量变量时,更好的方法是使用关联数组。

$values = array(
    'intro' => "Intro",
    'paragraphs' => "Paragraphs",
    'image' => "image.png",
    'conclusion' => "Conclusion",
    'h2' => "Heading"
);

Then you can use $values[$articletemplateAr[$i]] . 然后,您可以使用$values[$articletemplateAr[$i]]

The reason this is better is because the you can't inadvertently access unintended variables, you're limited to the elements in the array. 这样做更好的原因是因为您不能无意间访问意外变量,您只能使用数组中的元素。 This is especially important if the elements of $articletemplateAr come from an external source. 如果$articletemplateAr的元素来自外部来源,则这一点尤其重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM