全局变量使用

时间:2014-11-22 19:47:30

标签: php

我无法理解他们如何使用这种语言操作全局变量,我阅读文档并清楚地解释了所有内容,但是当我通过此代码进行申请时无法正常工作。 可能是我错了,帮我纠正。

我在电子表格php中声明了一个变量,我称之为变量$pubblica 在这一点上,我将进入一个以这种方式插入内容的函数:

function add()
{
    $GLOBALS['pubblica'] = "insert name";
}

我想现在变量$pubblica的内容是:“插入名称” 因此,我需要在另一个函数中使用带有此内容的变量,如下所示:

function esplore()
{
    echo "Contents of variables is $pubblica";
}

应该打印我这个内容:“插入名称”; 但我得到一个空白的信息,并不明白为什么。这有什么问题?

更新问题:

<?php

$GLOBALS['pubblica'];

function add()
{
   $GLOBALS['pubblica'] ="insert name";
}

function esplore()
{
   echo "Contents of variables is " . $GLOBALS['pubblica'];
}

?>

按下按钮时激活添加功能,其中称为esplore

2 个答案:

答案 0 :(得分:1)

您正在寻找的是:

<?php
function add()
{
    $GLOBALS['pubblica'] = "insert name";
}

function esplore()
{
    global $pubblica;
    echo "Contents of variables is $pubblica";
}

add();
esplore();
?>

如果您不使用global $pubblica;esplore()函数不知道$pubblica是全局变量并尝试在本地范围内找到它。

另一个故事是:

function esplore()
{
    echo "Contents of variables is " . $GLOBALS['pubblica'];
}

在这种情况下,很明显您正在处理(超级)全局变量,并且不需要额外的范围提示。

答案 1 :(得分:0)

问题是您使用表单传递数据。所以全局变量会丢失。您需要检索FORM变量。

下面的脚本将允许您在输入字段中输入您的变量,并在提交时保留它并显示结果。

<?php
$publicca=(isset($_POST['publicca']) ? $_POST['publicca'] : "");
// we check if there is the variable publicca posted from the form, if not $publicca is empty string
?>

<form action="#" method="post">
<input type="text" name="pubblica" value="<? echo $publicca; ?>" placeholder="insert name">
<!-- this input can be hidden, or visible or given by user, different formats, this is an example of user input -->
<button type="submit"> Pres to send the values </button>

<?

function esplore()
{
    global $pubblica;
    if (!empty($publicca)) echo "Contents of variables is $pubblica";
}
esplore();
?>
相关问题