欢迎使用 StackOverflow。 Majed 的答案是正确的,应该被标记为已接受的答案。不过,我建议您进行一些其他更改。
-
Separation of Concern: 更少的代码行并不一定意味着它更简单或更容易维护。一口大小的块和其中较少的决策分支确实如此。在其最基本的形式中,该原则要求您不要将您的算法逻辑与您的表示逻辑混合。
view.php
<style>
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
</style>
<body>
<table style="border: 1">
<tr>
<th>i</th>
<th>square</th>
<th>cube</th>
</tr>
<?php
foreach ($powers as $index => $power) {
echo "<tr><td>$index</td>";
foreach ($power as $value) {
echo "<td>$value</td>";
}
echo "</tr>";
}
?>
</table>
</body>
exponentHelpers.php
function square($x)
{
return $x * $x ;
}
function cube($y)
{
return $y * $y * $y ;
}
controller.php
require_once "exponentHelpers.php";
$base = 10;
$powers = [];
while($base--) { //Note, the self-decrementing short-hand will result in the values listed in reverse order.
//You could write it long-hand if you prefer, or call array_reverse() afterwards.
$powers[] = [
square($base),
cube($base),
];
}
require_once "view.php";
-
PSR2: 学习好习惯永远不要太早。 PSR2 基本上描述了格式化代码的行业标准,以使其看起来一致且易于阅读,无论是谁编写的。你有几处违规行为。
- 制表符应该是 4 个空格,而不是 5 个。
- 函数的左括号应该换行。
- 避免使用单行控制结构。即,为循环和 if 语句使用括号:
for ($i=1; $i <= 10 ; $i++) {
echo "
<tr>
<td>$i</td>
<td>".square($i)."</td>
<td>".cube($i)."</td>
</tr>";
}
-
Power function:你用square() 和cube() 函数重新发明了轮子。 Php 提供了一个pow($base, $exponent) 函数,它做同样的事情,并且不限于一个权力。所以这可以完全取消 exponentHelpers.php 部分。
-
符合 PSR2 的简写:如果您想使用它,完全是您的偏好,但是您可能会对这里的两个 PHP 位感兴趣,查看 view.php 部分中的循环。一种是array_map(),它允许imperative 数组循环和在同一行上检索结果。另一个是<?=,它是<?php echo ... 的HTML 模板简写。将它们放在一起,您可以更简洁地展示您的循环:
<?= array_map(function (array $power, $index) {
//Newlines are optional. Just makes the output a little easier to read.
$powerElms = preg_replace("/^.*$/", "<td>$0</td>", $power);
return "<tr>\n<td>$index</td>\n" . implode("\n", $powerElms) . "</tr>\n";
}, $powers, array_keys($powers)) //Missing semicolon is not a typo. It's not needed with this syntax. ?>