类方法代码应该直接访问外部变量吗? [英] Should class method code be accessing external variables directly?

查看:22
本文介绍了类方法代码应该直接访问外部变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些访问外部变量的 PHP 类方法.这些变量不作为参数传递,而是直接由方法中的代码使用.

I have certain PHP class methods that access external variables. These variables are not passed as arguments, but rather directly used by the code in the methods.

一种方法使用在配置文件中定义的变量,其目的是可供需要它的应用程序的每个部分使用.这对我来说似乎没问题.

One method uses a variable that is DEFINEd in a config file and whose purpose is to be available to every part of the app that needs it. This seems ok to me.

另一种方法直接访问 $_GET 变量.有一些代码可以处理未设置此 var 的情况,但不知何故这对我来说是一种气味.

The other method directly accesses a $_GET var. There is code that handles the case where this var is not set, but somehow this smells to me.

这两种情况是我应该做的还是应该有一个严格的传递作为参数的约定?

Are these two cases something I should be doing or should I have a strict pass-as-argument convention?

推荐答案

由于您已经在使用 PHP 类并且有可能更改架构,您应该尝试尽可能地将它们与外部变量分离.如果您需要使其向后兼容,您还可以设置默认变量.

Since you are already working with PHP classes and have the possibility to change the architecture you should try to decouple them as good as possible from outside Variables. If you need to make it backwards compatible you can also set default variables.

class Bla
{
    public function blaBla($var = false)
    {
        if(!$var && isset($_GET))
            $var = $_GET;
        // ...
    }
}

$bla = new Bla();
$bla->blaBla();
$bla->blaBla($_GET);

我也不喜欢define() 方法(我更喜欢像Zend Framework 注册表这样的单例变量注册表).一个大问题是您不能再更改定义.这可能好也可能不好.我正在开发一个软件,其中的define() 部分是加密的,因此即使它们在源代码中都有挂钩",也无法再更改它(但让类方法使用定义而不是将其作为争论……在我看来,这是非常糟糕的架构).

I don't like the define() method either (I prefer a singleton variable registry like the Zend Framework registry). One big Problem is that you can't change the defines anymore. This might be good or not. I was working on a piece of software where the define() part was encrypted and so there was no way to change that anymore even though they had "Hooks" all over the sourcecode (but let class methods use the defines instead of passing it as an argument... this is very bad architecture in my eyes).

这篇关于类方法代码应该直接访问外部变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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