[英]How to declare and use global variables
在此測試頁面https://wintoweb.com/sandbox/question_2.php上 ,訪問者可以在數據庫中進行搜索,並根據需要選中多個復選框。 單擊[接受...]按鈕后,我希望所有搜索的結果都顯示在“到目前為止的選擇”下。 現在,僅顯示上一次搜索。 我嘗試使用全局數組來存儲先前搜索的結果,並在每次新搜索時將其遞增。 那就是我有問題的地方。
在文件之上,我有:
<?php
global $all_authors;
array ($all_authors, '');
?>
在文件底部,我有:
<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
if(isset($_GET['search'])){
//echo 'Search</br>';
} elseif(isset($_GET['display_this'])) {
echo getNames();
}
function getNames() {
$rets = '';
if(isset($_GET['choices']) and !empty($_GET['choices'])){
foreach($_GET['choices'] as $selected){
$rets .= $selected.' -- ';
}
//array_push($all_authors, $rets); // This is the problem
//print_r($allAuthors); // this too
echo '</br><b>Your selections so far :</b></br>';
}
return $rets;
}
?>
預期:列出所有先前搜索的結果實際:由於array_push()存在問題,無法執行。 參見函數gatNames()
您應該在函數內部使數組成為全局數組,等等:
$all_authors = array();
在底部:
function getNames() {
global $all_authors;
// Do the rest of the stuff
}
您正在從getNames
函數返回$rets
,但沒有使用它。 您只需要使用此變量$rets
而不是全局變量。
if(isset($_GET['search'])){
//echo 'Search</br>';
} elseif(isset($_GET['display_this'])) {
$rets = getNames(); //The $rets will hold the value returned by your function getName().
if( !empty ( $rets ) ) {
echo '</br><b>Your selections so far :</b></br>';
echo $rets;
}
}
您可以從getNames
方法內部刪除echo語句。
function getNames() {
$rets = '';
if(isset($_GET['choices']) and !empty($_GET['choices'])){
foreach($_GET['choices'] as $selected){
$rets .= $selected.' -- ';
}
}
return $rets;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.