为了账号安全,请及时绑定邮箱和手机立即绑定

如何声明和使用全局变量

如何声明和使用全局变量

PHP
慕莱坞森 2021-11-19 17:12:48
在此测试页面https://wintoweb.com/sandbox/question_2.php 上,访问者可以在数据库中进行搜索并根据需要勾选任意数量的复选框。当单击按钮 [接受...] 时,我希望所有搜索的结果都显示在“到目前为止您的选择”下。现在,只显示最后一次搜索。我尝试使用全局数组来存储先前搜索的结果并在每次新搜索时增加它。这就是我有问题的地方。在文件顶部我有:<?php    global $all_authors;    array ($all_authors, '');?>在文件底部我有:<?phperror_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 tooecho '</br><b>Your selections so far :</b></br>';    }    return $rets;}?>预期:要列出所有先前搜索的结果 实际:由于 array_push() 问题,无法进行。参见函数 gatNames()
查看完整描述

2 回答

?
牧羊人nacy

TA贡献1862条经验 获得超7个赞

你正在$rets从你的getNames函数中返回,但没有使用它。你只需要使用这个变量$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;

    }

}


您可以从getNamesMethod 中删除 echo 语句。


function getNames() {

    $rets = '';

    if(isset($_GET['choices']) and !empty($_GET['choices'])){

      foreach($_GET['choices'] as $selected){

        $rets .= $selected.' -- ';

      }

    }

    return $rets;

}


查看完整回答
反对 回复 2021-11-19
?
SMILET

TA贡献1796条经验 获得超4个赞

您应该在函数内部使数组全局化,因此最重要的是:


$all_authors = array();

在底部:


function getNames() {

    global $all_authors;


    // Do the rest of the stuff

}


查看完整回答
反对 回复 2021-11-19
  • 2 回答
  • 0 关注
  • 172 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信