因爲你在頭兩行分配$yourname
和$compname
:
$yourname = htmlspecialchars($_POST['name']);
$compname = htmlspecialchars($_POST['compName']);
UPDATE您可以檢查這些在POST設置,因此以後不必檢查它們:
$yourname = isset($_POST['name']) ? htmlspecialchars($_POST['name']) : "oops, no value";
$compname = isset($_POST['compName']) ? htmlspecialchars($_POST['compName']) : "oops, no value";
即使爲NULL或爲空,它們也將始終設置。所以,你後來致電isset()
永遠是真的。 相反,你可以檢查它們是否爲空與empty()
功能:根據意見更正
UPDATE沒有必要的。你的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);
你應該閱讀這個:http://php.net/manual/en/language.variables.scope.php –