Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

php - Should class method code be accessing external variables directly?

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...