php - php获取全局var外部函数的值
问题描述
我在 php 中有这个测试函数:
funtion drop() {
global $test_end;
if(file_exists("test.php")) {
$ddr="ok";
}
$test_end="ready";
}
我知道如果我称它为drop()
“ok”,例如。
我的问题是:如果我在函数内部定义了一个全局变量,如何在函数内部以及执行时在函数外部输出这个变量的值?
例如,调用drop()
,然后echo $test_end;
在函数外部运行以获取值:
drop();
echo $test_end;
解决方案
不要使用全局变量,这是一个糟糕的设计,因为它会使您的代码混乱且难以阅读。还有更好的选择。
给定您的简单示例,您可以从方法中返回值:
function drop()
{
if(file_exists("test.php"))
{
$ddr="ok";
}
$test_end="ready";
return $test_end;
}
$test_end = drop();
如果您有更复杂的情况并且由于某种原因无法返回值,请通过引用传递变量,前缀为&
:
funtion drop(&$test_end)
{
if(file_exists("test.php"))
{
$ddr="ok";
}
$test_end="ready";
}
$test_end = null;
drop($test_end);
echo $test_end; // will now output "ready"
通过引用传递也不是一个很好的模式,因为它仍然会让你的代码混乱。
更多关于为什么全局变量不好
问题是,如果我正在查看您的代码,而我看到的只是:
drop();
echo $test_end;
我不知道 $test_end 是如何设置的或它的价值是什么。现在假设您有多个方法调用:
drop();
foo();
bar();
echo $test_end;
我现在必须查看所有这些方法的定义以找出 $test_end 的值是什么。这在较大的代码库中成为一个非常大的问题。
推荐阅读
- user-interface - 在遵守 FreeDesktop 标准的同时,在哪里为用户特定的应用程序安装图标?
- c# - 在 ASP.NET MVC 中更新多个选择下拉列表(选择 2)
- asp.net-web-api - Azure 托管服务出错“发送请求时出错”
- json - 如何从 JSON API 调用项目并添加到 TabBar - Flutter
- java - 为什么我的多线程程序会出现三种结果?
- google-drive-api - 无法使用邮递员在 Google Drive 中创建文件夹
- javascript - DataTable 中的 rowsPerPageOptions 未显示
- android - 我的 build.gradle 文件出现错误
- reactjs - 在 docker 容器中使用 React 部署 ExpressJS
- c# - 有没有办法使用谷歌应用脚本识别谷歌演示文稿中的隐藏幻灯片?