您可以$output在主脚本中定义,并将其导入到函数中:
function output()
{
global $output;
Run Code Online (Sandbox Code Playgroud)
这可能适用于您手头的情况.但是,将全局变量空间与这样的东西一起使用被认为是不好的做法,这是正确的.(相信我,我已经做了多年.:)
还有一些其他方法可以更好地实现长期代码质量和可维护性.
全局配置数组
您可以为所有全局设置保留一个全局数组.在主脚本中的某处执行此操作:
$config = array();
$config["output"] = "<html>.......</htmL>";
$config["user_language"] = "en";
.....
Run Code Online (Sandbox Code Playgroud)
您将配置数组导入到函数中,如下所示:
function output()
{ global $config;
echo $config["output"];
Run Code Online (Sandbox Code Playgroud)
注册表模式
如果你想做一些阅读,你可以使用更高级的东西,如注册表模式.这里显示的代码段看起来是一个很好的注册表示例.在Zend框架也有这一类.
但是像注册表这样的东西真的非常先进,而且在这一点上可能不是必需的.我建议使用一个中央配置数组.如果需要更复杂的东西,配置数组很容易找到和替换.
欢迎使用返回和传递参数:
不要使用 global它,它打破了封装,面向对象编程的基石之一,并且可能导致难以置信的维护代码.
<?php
function doSomethingInDb(){
$value = db_result(); //something from the database, this is psuedo code
return $value
}
function displaySomethingFromDb($input){
echo($input); //or some other way of displaying
}
//calulate results
$output = doSomethinginDb();
//do other stuff...
//output the result when you need it...
displaySomethingFromDb($output);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5843 次 |
| 最近记录: |