如果类方法code可以直接访问外部变量? [英] Should class method code be accessing external variables directly?

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

问题描述

我有访问外部变量一定的PHP类方法。这些变量不会作为参数传递,但在方法而直接使用由code。

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变种。有code处理,其中该变种没有被设置的情况下,但不知何故,这气味给我。

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);

我不喜欢的定义()方法是(PFER如Zend框架注册表变量单身注册表我$ P $)。
一个大问题是,你不能改变的定义了。这可能是好还是不好。我工作的一个软件,其中定义()部分是加密的,所以没有办法改变了,即使他们有挂钩遍源$ C ​​$ C(但让类方法使用的定义,而不是把它当作一个说法......这是在我眼里很糟糕的架构)。

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).

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

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