如何在 php 中使用函数中的循环变量作为同一函数的参数


How can use a loop variable in function as a parameter of same function in php

<?php
klmn("<input type='button'  value='$x'>");
function klmn($st){   
    echo "<table>";
    for ($x=1; $x<=12; $x++) 
    {
        echo "<td>".$st ." </td>";
    }
    echo "</table>";
}

当 ı 运行此代码时,ı 看不到从 1 到 12 的按钮值

function klmn($st){   
    echo "<table>";
    for ($x=1; $x<=12; $x++) 
    {
        echo "<td>". str_replace('$x', $x, $st) ." </td>";
    }
    echo "</table>";
}
klmn('<input type="button"  value="$x">');

当你传递参数时,$x是当前的var(在你的函数范围之外(,可能你收到了未定义变量的通知。

您应该对占位符进行str_replace

klmn("<input type='button'  value=''$x'>"); // note the backslash '$x
function klmn($st){   
    echo "<table>";
    for ($x=1; $x<=12; $x++) 
    {
        echo "<td>".str_replace('$x',$x,$st) ." </td>";
    }
    echo "</table>";
}