测试用户输入密码字的简单游戏无法按预期工作。评估条件时,屏幕上不会返回任何内容。我很确定这是一个简单的问题,但这里的大多数问题/答案比我相信的要复杂得多。
这就是我正在使用的。要求用户输入正好9个字符的单词,并且必须包含@符号。所有键盘字符也都有效。如果未满足要求,则回应用户,如果满足要求,则回应成功。
<?php
if (!isset($secret_word)) {
$secret_word = ''; }
/* prompt user to enter a secret word that contains 9 characters of which one must be @ sign and all keyboard characters are allowed. if the secret word isn't correct output what is wrong with the word. */
#get user input
$secret_word = filter_input(INPUT_POST, 'secret_word');
$wordTest = secretWord();
function secretWord() {
if (strlen($secret_word) < 9) {
echo "Secret word is too short!"; }
if (strlen($secret_word) > 9) {
echo "Secret word is too long!"; }
if (!preg_match("@", $secret_word)) {
echo "Secret word must contain @ sign"; }
if (strlen($secret_word) == 9 && preg_match("@", $secret_word)){
echo "$secret_word contains 9 characters and one sign.";}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="q4.css">
<title>Untitled Document</title>
</head>
<body>
<div class="header">
<header><h1>Secret Scroll Game</h1></header>
</div>
<div class="output">
<p><?php echo $wordTest(); ?></p>
</div>
<div class="link">
<a href="q4_index.html">Back To Homepage</a>
</div>
</body>
</html>
答案 0 :(得分:1)
Jeez,我看的越多,我在这里的问题代码就越错误了......请读到这个答案的底部......
echo $wordTest();
要求PHP返回一个函数的结果,但函数尚未定义,你可能会打算回显$ wordTest那个没有附加括号的变量。
所以
更改
echo $wordTest();
到
echo $wordTest;
<强> P.S:强>
如果您在脚本上启用了PHP错误报告,那么您自己就会很容易地发现这一点,正如Fred-ii所暗示的那样。 Research Error reporting on StackOverflow.
<强> P.P.S:强>
你的功能很乱,你的功能应该return
一个值,而不是直接打印到屏幕上。因此,您需要将echo
文本的所有出现替换为return
一个已定义文本的变量,因此:
function secretWord() {
if (strlen($secret_word) < 9) {
echo "Secret word is too short!"; }
应该成为:
function secretWord() {
if (strlen($secret_word) < 9) {
$var = "Secret word is too short!";
}
...
//etc. etc. do this for each text if statement... then:
return $var; //give the text value back to were the
//function was called from.
} //this closes the function.
这意味着当你有:
$wordTest = secretWord();
$wordTest
将等于secretWord()
函数返回的值。
如果没有return
,则$wordTest
的值将始终为NULL
。
更多信息:
$secret_word
的范围[意味着此值是否已定义]在您声明的函数中 不 ,因此您需要提供此值为函数以获得正确的响应。
所以:声明你的函数并将变量放在括号中:
function secretWord($givenWord) {
然后在函数重构中将所有变量称为$secret_word
到$givenWord
。
然后在函数外部,你需要通过引用将秘密字传递给你的函数,所以:
$wordTest = secretWord($secret_word);
或
echo secret_word($secret_word);
或者,因为您实际上没有使用$wordTest
变量做任何其他事情,所以您并不需要它,所以在HTML中您可以这样做:
<div class="output">
<p><?php echo secretWord(); ?></p>
无论函数返回是什么,它都会回显。
同样$_POST
输入不是HTML(特殊)字符,它们将是提交表单的字符集中的字符,因此您当前的搜索模式正在寻找一串字符永远不会出现作为另一个角色的替代品。
您需要将此处建议的每个更改应用于更改所适用的代码中的所有实体,我不会为您重写整个代码。