首页 > 解决方案 > 使服务器可以理解 php 的循环,而不仅仅是回显代码

问题描述

我必须添加很长的代码

 $somephpcode->Cell($string1);
 $somephpcode->Cell('Figure 1');
 $somephpcode->Cell($string2);
 $somephpcode->Cell('Figure 2');
 $somephpcode->Cell($string3);
 $somephpcode->Cell('Figure 3');
 ...

我想用循环让它更快。我可以这样:

for ($x = 1; $x <= 25; $x++) {
    $somestring = "\$somephpcode->Cell(\$string$x);\$somephpcode->Cell('Figure $x');";
    echo $somestring;
}

它会回显正确的代码。但是我的初学者问题是如何使服务器可以理解,而不仅仅是返回(显示)代码?我应该用什么代替回声?可能吗?

标签: phploops

解决方案


无需任何重大更改,您只需创建一个包含要引用的变量名称的字符串,然后使用 PHP 的“变量变量”功能来取消引用它:

for ($x = 1; $x <= 25; $x++) {
    $varName = 'string' . $x;
    // So now $varName contains a string like "string1", and we use two dollar signs here:
    $somephpcode->Cell($$varName);
    $somephpcode->Cell('Figure ' . $x);
}

但是,任何时候你有变量命名为 var1、var2、var3,你真的应该考虑使用数组来代替。例如:

$strings = ['first string', 'second string', 'third string', ... ];

然后您可以通过从零开始的数字索引来引用第一个字符串,例如$strings[0]. 这使您的代码更清晰:

for ($x = 1; $x <= 25; $x++) {
    $somephpcode->Cell($strings[$x - 1]);
    $somephpcode->Cell('Figure ' . $x);
}

推荐阅读