好吧所以我在这里尝试练习一些PHP(我是一个超级初学者)这么长的故事, 我将表单元素放在一个页面中,将其传递给进程php。 我只是乱七八糟地试图看看到目前为止我学到了什么。我没有得到任何错误,只是不明白为什么它不起作用。
<?php
$yourname = htmlspecialchars($_POST['name']);
$compname = htmlspecialchars($_POST['compName']);
$response = array("please enter correct information","hmm" . "$yourname");
function nametest() {
if (!isset($yourname)){
$yourname = $response[0];}
else {
$yourname = $response[1];;
}
}
?>
<?php nametest(); ?>
我想要做的是,如果名称未设置,则使变量等于响应内的值。
答案 0 :(得分:0)
尝试
function nametest() {
if (!isset($yourname)){
$yourname = $response[0];
} else {
$yourname = $response[1];
}
return $yourname;
}
print nametest();
该函数需要返回要打印的值。我也注意到你有两个;在第5行后面。
答案 1 :(得分:0)
因为您要在前两行分配$yourname
和$compname
:
$yourname = htmlspecialchars($_POST['name']);
$compname = htmlspecialchars($_POST['compName']);
更新您可以检查这些是否在POST中设置,因此不需要稍后检查:
$yourname = isset($_POST['name']) ? htmlspecialchars($_POST['name']) : "oops, no value";
$compname = isset($_POST['compName']) ? htmlspecialchars($_POST['compName']) : "oops, no value";
即使NULL或为空,也始终设置它们。因此,您以后对isset()
的来电始终是真的。
相反,您可以使用empty()
函数检查它们是否为空:
更新根据评论中的更正,不需要。您的isset()
应该有效。
// Check with empty()
// but still won't work properly. keep reading below...
function nametest() {
if (!empty($yourname)){
$yourname = $response[0];}
else {
$yourname = $response[1];;
}
}
然而,这里存在可变范围的另一个问题。除非您将这些变量作为参数传递或使用global
关键字,否则变量在函数内部不可用:
// $yourname is passed as a function argument.
function nametest($yourname, $response) {
if (!empty($yourname)){
$yourname = $response[0];}
else {
$yourname = $response[1];;
}
}
到达那里......现在你的函数指定$yourname
,但它不会返回或打印任何值。添加一个return语句,然后你可以回显结果:
function nametest($yourname, $response) {
if (!empty($yourname)){
$yourname = $response[0];}
else {
$yourname = $response[1];;
}
// Add a return statement
return $yourname;
}
// Now call the function, echo'ing its return value
echo nametest($yourname, $response);
答案 2 :(得分:0)
变量范围是这里最大的错误,你的函数无法“看到”你在它之外创建的变量,执行此操作:
<?php
.
.
.
function nametest($yourname, $response) { // This creates two new variables that
// are visible only by this function
if (!isset($yourname)){
$yourname = $response[0];
} else {
$yourname = $response[1]; // Get rid of the extra semicolon
}
return $yourname; // This $yourname is only visible by this function so you
// need to send it's value back to the calling code
}
?>
<?php nametest($yourname, $response); ?> // This sends the values of the
// variables that you created at the
// top of this script