首先,我是PHP新手,我还在学习,这个网站对我的学习非常有帮助,所以感谢所有贡献者
我需要在第二个$t1selected
函数中访问两个变量$t2selected
和isset()
。
我真的尝试过我所知道的一切。我仍在学习和使用本书“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_dump我得到两个变量值
以下是我的第二部分
的一部分// 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
答案 0 :(得分:1)
不要使用global关键字只是将变量的值传递给函数。
回显函数内部的值。
传递像这样的值
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;
}
}
}
答案 1 :(得分:0)
这不是编码的好习惯,但根据您提到的另一个选项是:
<?php
define('T1_SELECT',$t1select);
define('T2_SELECT',$t2select);
?>
它将在全球范围内提供,您可以随时随地在完整的应用程序中访问它 T1_SELECT 和 T2_SELECT。
由于 阿米特