临时变量 [英] Temporary Variable

查看:36
本文介绍了临时变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数可以从数据库中检索一些数据,将其格式化为 HTML,然后将此 HTML 存储到一个变量 $output 中.问题是 $output 现在不能在屏幕上回显,只有在其他功能运行后才能回显.此外,必须在此阶段检索此数据,而不是稍后.

I have a function that retrieves some data from the database, formats it as HTML and then stores this HTML into a variable, $output. The problem is that $output cannot be echoed on the screen now, only later, after other functions run. Also this data must be retrieved at this stage, not later.

那么,在开始输出到屏幕后,如何在另一个函数中调用这个 $output 变量?

So how can I call this $output variable in another function, after output to the screen has started?

推荐答案

您可以在主脚本中定义 $output,并将其导入到函数中:

You could define $output in the main script, and import it into a function:

function output() 
 {  
   global $output;

这可能适用于您手头的情况.但是,将全局变量空间用于这样的东西被认为是不好的做法,这是正确的.(相信我,我已经这样做了.:)

This will probably work for your situation at hand. However, it is considered bad practice to use the global variable space with stuff like this, and rightly so. (Believe me, I've done it for years. :)

还有一些其他方法可以更好地提高长期代码质量和可维护性.

There are some other approaches that are better for long-term code quality and maintainability.

全局配置数组

您可以为所有全局设置保留一个全局数组.在主脚本的某个地方执行此操作:

You could either keep one global array for all global settings. Do this somewhere in your main script:

$config = array();
$config["output"] = "<html>.......</htmL>";
$config["user_language"] = "en";
.....

你像这样将配置数组导入到函数中:

you import the configuration array into the function like so:

function output()
 { global $config;
   echo $config["output"];

注册表模式

如果你想做一些阅读,你可以使用更高级的东西,比如注册表模式.此处 显示的代码段看起来是一个很好的注册表示例.Zend Framework 也有一个用于此的类.

if you want to do some reading, you could use something more advanced like the Registry Pattern. The snippet shown here looks a nice example for a registry. The Zend Framework also has a class for this.

但是诸如注册表之类的东西真的非常先进,此时您可能不需要.我建议使用一个中央配置数组.如果需要更复杂的东西,配置数组很容易找到和替换.

But things like a Registry are really, really advanced, and probably not necessary for you at this point. I would suggest using one central config array. Should the need for something more complex arise, the config array is easy to find and replace.

上下文:PHP 中的全局变量是否被认为是不好的做法?

这篇关于临时变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆