gpt4 book ai didi

php - 如何修复 PHP 中的 "Undefined variable"错误?

转载 作者:可可西里 更新时间:2023-11-01 13:13:21 24 4
gpt4 key购买 nike

今天,我开始学习PHP了。而且,我已经创建了我的第一个 PHP 文件来测试不同的变量。你可以看到我的文件如下。

<?php
$x = 5; // Global scope

function myTest()
{
$y = 10; // Local scope
echo "<p>Test variables inside the function:<p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
}

myTest();

echo "<p>Test variables outside the function:<p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
?>

当我在浏览器中运行这个文件时,我发现了以下错误。

Notice: Undefined variable: x in /opt/lampp/htdocs/anand/php/index.php on line 19

Notice: Undefined variable: y in /opt/lampp/htdocs/anand/php/index.php on line 29

我该如何解决相关问题?

最佳答案

第一个错误($x 未定义)是因为默认情况下没有将全局变量导入函数(与“ super 全局变量”相反)。

您需要告诉您的函数您正在引用全局变量 $x:

function myTest()
{
global $x; // $x refers to the global variable

$y=10; // local scope
echo "<p>Test variables inside the function:<p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
}

否则,PHP 无法判断您是否使用同名的局部变量来隐藏全局变量。

第二个错误($y 未定义)是因为局部作用域就是局部作用域。重点是 $y 不会“泄漏”出函数。当然,您以后不能在代码中访问 $y,在定义它的函数之外。如果可以的话,它与全局没有什么不同。

关于php - 如何修复 PHP 中的 "Undefined variable"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20391807/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com