我有这段代码,基本上如果函数“minmax”里面的代码中的“IF”语句为真,我希望程序从头开始。 我不确定如何实现这个逻辑,有人可以帮助
<?php
// user to enter the number of heads
echo "Enter the number of heads: " . PHP_EOL;
// the script will wait here until the user has entered something and hit ENTER
$inhead = read_stdin();
// user to enter the number of legs
echo "Enter the number of legs: " . PHP_EOL;
// the script will wait here until the user has entered something and hit ENTER
$inleg = read_stdin();
function read_stdin()
{
$fr=fopen("php://stdin","r"); // open our file pointer to read from stdin
$input = fgets($fr,128); // read a maximum of 128 characters
$input = rtrim($input); // trim any trailing spaces.
fclose ($fr); // close the file handle
return $input; // return the text entered
}
//function to evalute if th euser has provided the right number of legs
function minmax($number)
{
global $inhead,$inleg;
$min = 2*$inhead;
$max = 4*$inhead;
if ($number<$min || $number>$max)
{
echo "please enter a number between $min and $max to get the correct result";
echo "\n";
echo "\n";
}
}
//function to calculate the number of heads and legs
function get_the_result($noofheads,$nooflegs)
{
$x=($nooflegs-(2*$noofheads))/2;
$y=$noofheads - $x;
echo "The num of dogs are $x";
//echo "/n";
echo "The no of humans are $y";
}
minmax($inleg);
get_the_result($inhead,$inleg);
?>
答案 0 :(得分:0)
您可以使用goto:
location:
//...
goto location;
在您的情况下,您需要检查函数是否存在,不要尝试使用function_exists
声明它们两次。
虽然这是可能的,但我建议您重写代码,因为这种方法显然是不可行的。
答案 1 :(得分:0)
如果您的验证不满意,为什么不重新加载页面? 尝试使用Session来显示错误消息。
<?php
session_start();
if(isset($_SESSION['error'])){
echo $_SESSION['error'];
unset($_SESSION['error']);
}
// user to enter the number of heads
echo "Enter the number of heads: " . PHP_EOL;
// the script will wait here until the user has entered something and hit ENTER
$inhead = read_stdin();
// user to enter the number of legs
echo "Enter the number of legs: " . PHP_EOL;
// the script will wait here until the user has entered something and hit ENTER
$inleg = read_stdin();
function read_stdin()
{
$fr=fopen("php://stdin","r"); // open our file pointer to read from stdin
$input = fgets($fr,128); // read a maximum of 128 characters
$input = rtrim($input); // trim any trailing spaces.
fclose ($fr); // close the file handle
return $input; // return the text entered
}
//function to evalute if th euser has provided the right number of legs
function minmax($number)
{
global $inhead,$inleg;
$min = 2*$inhead;
$max = 4*$inhead;
if ($number<$min || $number>$max)
{
$_SESSION['error'] = "please enter a number between $min and $max to get the correct result";
echo("<meta http-equiv='refresh' content='1'>");
}
}
//function to calculate the number of heads and legs
function get_the_result($noofheads,$nooflegs)
{
$x=($nooflegs-(2*$noofheads))/2;
$y=$noofheads - $x;
echo "The num of dogs are $x";
//echo "/n";
echo "The no of humans are $y";
}
minmax($inleg);
get_the_result($inhead,$inleg);
?>
请注意,此处不能使用标头重新加载,因为某些元素已被回显。并且您可以更改内容的值以延迟页面重新加载的时间(值以秒为单位)。