Php 全局变量使用
我不明白他们是如何用这种语言操作全局变量的,我阅读了文档,所有的内容都解释得很清楚,但是当我通过这段代码去应用时,它是不起作用的。 可能是我做错了什么,帮我纠正一下 我在电子表格php中声明一个变量,我调用变量Php 全局变量使用,php,Php,我不明白他们是如何用这种语言操作全局变量的,我阅读了文档,所有的内容都解释得很清楚,但是当我通过这段代码去应用时,它是不起作用的。 可能是我做错了什么,帮我纠正一下 我在电子表格php中声明一个变量,我调用变量$pubblica 此时,我将进入一个函数,以这种方式插入内容: function add() { $GLOBALS['pubblica'] = "insert name"; } 我想变量$pubblica的内容现在是:“insert name” 因此,我需要在另一个函数中使用包
$pubblica
此时,我将进入一个函数,以这种方式插入内容:
function add()
{
$GLOBALS['pubblica'] = "insert name";
}
我想变量$pubblica
的内容现在是:“insert name”
因此,我需要在另一个函数中使用包含此内容的变量,如下所示:
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'];
}
?>
当您按下一个按钮时,添加功能被激活,在该按钮中,您要查找的内容是:
<?php
function add()
{
$GLOBALS['pubblica'] = "insert name";
}
function esplore()
{
global $pubblica;
echo "Contents of variables is $pubblica";
}
add();
esplore();
?>
在这种情况下,很明显,您正在处理一个(超级)全局变量,不需要额外的范围暗示 问题是您使用表单传递数据。所以全局变量丢失了。您需要检索表单变量 下面的脚本将允许您在输入字段中输入变量,提交时将保留该变量并显示结果
<?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();
?>
阅读此页面变量在PHP中始终是局部范围的,除非您根据global
关键字(第二个函数)或$GLOBALS[]
查找邀请它们(仅在add
中邀请)。快速提醒:当某些东西不起作用时,启用error\u reporting
。我得到以下信息:注意:未定义变量:Pubblicab在开始使用global之前,我建议您阅读,因为正如上面所解释的,global是邪恶的。根据您的最后一句话,似乎您用按钮调用了另一个脚本,对吗?然后必须实现不同的数据传递技术,全局变量仅在当前脚本中是全局的$_GET或$\u POST可能是您的解决方案,但请向我们展示包含“按钮”的代码。如何将全局变量作为参数传递?@Heisenberg与其他所有变量的传递方式相同,但如果您有一个全局变量,您不必传递它,因为它是全局变量,可以在任何地方使用(除非它在局部范围内被覆盖).嗯,我代码中的这个解决方案不起作用。。$pubblica的内容是blank@Heisenberg什么?我发布的代码确实有效()。当然,您必须像我一样首先调用add()
。我更新了问题,我想我已经成功地实现了它的工作代码。问题是变量总是空的。
<?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();
?>