如果在函数之前已经定义了php未定义的变量,我该如何修复该变量



我正在尝试制作两个函数,以根据日出和日落时间获得亮小时数和暗小时数。在将我的代码转移到函数中之前,一切都很好,但现在它无法定义我的变量,尽管这些变量完全在函数之外打印。我在这里看了一些答案,但每一个答案似乎都建议使用全局或通过传递变量作为自变量。使用global会导致它根本不起作用,并且将变量作为参数传递不会改变任何事情。我有两个文件,一个包含我的函数,另一个用于打印它们。

错误是:

Notice: Undefined variable: sunset in C:xampphtdocstest.php on line 13
Notice: Undefined variable: sunrise in C:xampphtdocstest.php on line 13

我的功能如下:

<html>
<body>
<?php
$lat = 38.7;
$long = -75;
$sunrise = (date_sunrise(time(),SUNFUNCS_RET_STRING,38.7,-75,75,-5)); //get local time, offset -5 hours from gmt
$sunset = (date_sunset(time(),SUNFUNCS_RET_STRING,38.7,-75,75,-5));   //get local time, offset -5 hours from gmt
function light(){ //passing the variables gave me the same result
(strtotime($sunset) - strtotime($sunrise))/3600;   //$sunset and $sunrise are undefined
}
function dark(){
24 - light(); //same issues as light()
}
?>
</body>
</html>

这就是我用来打印所有东西的东西:

<?php
require "test.php"; //name of function page
echo "Date: " . date("D M j Y");
echo "<br>Latitude: " . $lat;
echo "<br>Longitude: " . $long . "<br>";
//these variables are the ones that are undefined in my function, but they're printing just fine here
echo "<br>Sunrise Time: " . $sunrise; 
echo "<br>Sunset Time: " . $sunset . "<br>";
echo "<br>Hours of Light: " . (round(light(),2)); //round to two decimals
echo "<br>Hours of Dark: " . (round(dark(),2));   //round to two decimals
?>

我在这里有点不知所措,我想也许是因为我在使用自己的预构建函数,但我确信这是可能的。在过去的一天左右时间里,我一直在尝试解决这个问题,但没有取得任何进展,所以如果能提供任何帮助,我们将不胜感激。非常感谢。

您需要了解更多关于变量作用域的信息。不能从函数内部访问外部变量。

相反,修改你的功能如下:

<?php
$lat = 38.7;
$long = -75;
$sunrise = (date_sunrise(time(),SUNFUNCS_RET_STRING,38.7,-75,75,-5)); //get local time, offset -5 hours from gmt
$sunset = (date_sunset(time(),SUNFUNCS_RET_STRING,38.7,-75,75,-5));   //get local time, offset -5 hours from gmt
function light($sunset, $sunrise){ //passing the variables gave me the same result
(strtotime($sunset) - strtotime($sunrise))/3600;
}
$light = light($sunset, $sunrise)
function dark($light){
24 - $light;
}
?>

我实际上能够通过阅读这里来解决这个问题https://www.php.net/manual/en/language.variables.scope.php

事实证明,我需要做的是在函数本身中将变量定义为全局变量,而不是在函数之外!

最新更新