【问题标题】:How can I call the function in diferent block in PHP?如何在 PHP 的不同块中调用函数?
【发布时间】:2020-07-01 05:21:52
【问题描述】:

php 假人在这里。 我的老师给了我们这段代码来学习 For 循环以及如何在 PHP 中使用函数,当我在 Sublime Text 3 上编写它时它不起作用,我不知道为什么,有帮助吗?

<!DOCTYPE html>
<html>
<head>
    <title>CICLO FOR Y FUNCTION</title>
</head>
<body>

    <h1>Uso de funciones (function) y el ciclo FOR</h1>
    <h1>helo</h1>
    <?php
        function muestra($valor){
            if($valor<0){
                $color = "red";
                echo "<td><font color='$color'></font></td><br>\n";
            }
            else{
                $color = "blue";
                echo "<td><font color='$color'></font></td>\n";
            }
        }
    ?>
        <table border="1">
    <?php
        for($x=0; $x<=2; $x+=0.01){
            echo "<tr>";
            muestra($x);
            muestra(sin($x));
            muestra(cos($x));
            echo "</tr>";
        }
    ?>
</body>
</html>

Capture

【问题讨论】:

  • 你没有在 之间放任何东西

标签: php html function for-loop


【解决方案1】:
  1. 去掉&lt;br&gt;标签,这里没用!
  2. 您需要在单元格中显示数据才能看到带有颜色的结果。
  3. 你应该使用&lt;span style="color: &lt;your color&gt;;"&gt;而不是&lt;font color=""&gt;...为什么? &lt;font&gt; 标签在 HTML 5 中已弃用(由 DOCTYPE 指示)!

您的代码应如下所示。

<!DOCTYPE html>
<html>
<head>
    <title>CICLO FOR Y FUNCTION</title>
</head>
<body>
    <h1>Uso de funciones (function) y el ciclo FOR</h1>
    <h1>helo</h1>
    <?php
    function muestra($valor) {
        if ($valor < 0) {
            $color = "red";
            echo "<td><span style=\"color: $color;\">{$valor}</span></td>\n";
        } else {
            $color = "blue";
            echo "<td><span style=\"color: $color;\">{$valor}</span></td>\n";
        }
    }
    ?>
    <table border="1">
        <?php
        for ($x = 0; $x <= 2; $x += 0.01) {
            echo "<tr>";
            muestra($x);
            muestra(sin($x));
            muestra(cos($x));
            echo "</tr>";
        }
        ?>
    </table>
</body>
</html>

更好的编码风格是只有一个echo 来输出您的表格数据,并在函数内部使用return 而不是echo。要将其存档并获得更清晰的代码,您可以重写上面的示例,如下所示。

<?php

function muestra($valor) {
    if ($valor < 0) {
        return '<td><span style="color: red;">' . $valor . '</span></td>' . PHP_EOL;
    }
    return '<td><span style="color: blue;">' . $valor . '</span></td>' . PHP_EOL;
}

$output = '';
for ($x = 0; $x <= 2; $x += 0.01) {
    $output .= '<tr>';
    $output .= muestra($x);
    $output .= muestra(sin($x));
    $output .= muestra(cos($x));
    $output .= '</tr>';
}

?>
<!DOCTYPE html>
<html>
<head>
    <title>CICLO FOR Y FUNCTION</title>
</head>
<body>
    <h1>Uso de funciones (function) y el ciclo FOR</h1>
    <h1>helo</h1>
    <table border="1">
        <?php echo $output; ?>
    </table>
</body>
</html>

【讨论】:

    猜你喜欢
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    • 2023-03-17
    • 1970-01-01
    • 2011-07-17
    相关资源
    最近更新 更多