需要帮助在 PHP 中重构全局变量
我有一个配方脚本,其中包含一些使用全局变量编写的 PHP 代码。有人能告诉我一个我可以遵循的开始交换全局变量的一般过程(或者可以说是操作顺序)吗?这是一个例子:
function computeCost() {
global $DB_LINK;
$this->loadIngred();
if ($this->liquid == $DB_LINK->true)
$liquid = true;
$amount = Units::convertTo($this->amount, $this->unitMapping, $this->unit,
$this->liquid);
return ($this->amount * $this->cost);
}
I have a recipe script with some PHP code that was written with Global Variables. Would anyone be able to tell me a general process (or order of operations so-to-speak) that I could follow to begin swapping out the global variables? Here's an example:
function computeCost() {
global $DB_LINK;
$this->loadIngred();
if ($this->liquid == $DB_LINK->true)
$liquid = true;
$amount = Units::convertTo($this->amount, $this->unitMapping, $this->unit,
$this->liquid);
return ($this->amount * $this->cost);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以像这样将其传递到函数中,而不是使用全局变量:
并像这样调用函数:
这样,不需要全局变量(这更好),并且可以将数据传递到函数中。因此,该函数并不像人们想象的那样与外部存在依赖关系。
Instead of using a global variable you could pass it into the function like this:
And call the function like this:
This way, no Globals are needed (and this is better) and you pass the data into the function. So the function does not have a dependency with the outside, as it is supposed to be.