Php 需要访问isset函数外部的变量

Php 需要访问isset函数外部的变量,php,sql,function,Php,Sql,Function,首先,我是PHP新手,我还在学习,这个网站在我的学习上帮了我很大的忙,所以感谢所有的贡献者 我需要在第二个isset()函数中访问两个变量$t1selected和$t2selected 我真的尝试了我所知道的一切。我仍在学习和使用《PHP完整参考》一书,这本书只提到,当您将变量声明为全局变量时,您可以跨所有函数访问它们……在这种情况下,显然不是这样 以下是我的第一个功能的一部分: var_dump确认全局变量持有正确的值 // This code gets executed after form

首先,我是PHP新手,我还在学习,这个网站在我的学习上帮了我很大的忙,所以感谢所有的贡献者

我需要在第二个
isset()
函数中访问两个变量
$t1selected
$t2selected

我真的尝试了我所知道的一切。我仍在学习和使用《PHP完整参考》一书,这本书只提到,当您将变量声明为全局变量时,您可以跨所有函数访问它们……在这种情况下,显然不是这样

以下是我的第一个功能的一部分:

var_dump确认全局变量持有正确的值

// This code gets executed after form has been submitted
function getPlayers(){
if (isset($_POST['select'])) 
{
    global $t1select;
    global $t2select;
 // get 1st team selected
 foreach($_REQUEST["team1_select"] as $t1select) 
 {
    $t1select = $t1select;
 } //end foreach

 // get second team selected
 foreach($_REQUEST["team2_select"] as $t2select) 
 {
  $t2select = $t2select;
 } //end foreach

var_dump($t1select);
var_dump($t2select);

//SOME MORE CODE
现在,在我的第二个函数中,我尝试引用两个变量
$t1selected
$t2selected
对它们进行var_转储,两个变量的值都为null

下面是我的第二个功能的一部分

// THIS PART IS TO GET THE STARTING PLAYERS
function PlayerAttributes(){
if (isset($_POST['teamselect'])) {
global $t1select;
global $t2select;
var_dump($t1select);
var_dump($t2select);
 // Get Selected Team For Team1
 foreach($_REQUEST['team1selected'] as $team1players) {
$team1players;
 } //end foreach1
 foreach($_REQUEST['team2selected'] as $team2players) {
   $team2players;
 } //endfor each2
//SOME MORE CODE
我的问题

// THIS PART IS TO GET THE STARTING PLAYERS
function PlayerAttributes(){
if (isset($_POST['teamselect'])) {
global $t1select;
global $t2select;
var_dump($t1select);
var_dump($t2select);
 // Get Selected Team For Team1
 foreach($_REQUEST['team1selected'] as $team1players) {
$team1players;
 } //end foreach1
 foreach($_REQUEST['team2selected'] as $team2players) {
   $team2players;
 } //endfor each2
//SOME MORE CODE

如何在代码中的所有函数中访问两个变量
$t1selected
$t2selected
,不要使用全局关键字,只需将变量的值传递给函数即可

回显函数中的值

像这样传递值

PlayerAttributes($t1select,$t2select);





function PlayerAttributes($t1select,$t2select){
        if (isset($_POST['teamselect'])) {

            var_dump($t1select);
            var_dump($t2select);
            // Get Selected Team For Team1
            foreach($_REQUEST['team1selected'] as $team1players) {
               echo $team1players;
            } //end foreach1
            foreach($_REQUEST['team2selected'] as $team2players) {
               echo $team2players;
            }

        }
        }

这不是很好的编码实践,但根据您提到的场景,另一个选项是:

<?php
define('T1_SELECT',$t1select);
define('T2_SELECT',$t2select);
?>

它将在全球范围内可用,您可以通过 T1_选择 及 T2_选择

谢谢
Amit

不要使用全局关键字!为什么不把它们作为参数传递给函数呢?同时
$t1select=$t1select
$t1select
被声明为全局时,会弄乱您的编码逻辑。@ShankarDamodaran这样做会导致错误“注意未定义的变量”,然后会导致错误“未定义的变量:t1select”“未定义的变量:t2select”你传递了值吗?我传递了包含该值的变量