参数与成员变量 [英] Parameter vs. Member variables

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

问题描述

我最近一直在与其他人的代码一起工作,我意识到这个人关于私有变量和方法参数的哲学与我完全不同.我通常认为私有变量仅应在以下情况下使用:

I've recently been working with someone else's code and I realized that this individual has a very different philosophy regarding private variables and method parameters than I do. I generally feel that private variables should only be used in a case when:

  1. 该变量需要存储以便以后调用.
  2. 存储在变量中的数据在类中全局使用.
  3. 当变量需要全局操作时(与通过每种类方法读取变量的需求明显不同).
  4. 何时可以大大简化编程. (诚​​然含糊不清,但在很多情况下都必须避免将自己画在一个角落里.)

(我承认,上面的许多内容都是重复的,但是它们看起来似乎各有不同,值得进行这样的处理……)

似乎这是防止意外更改变量的最有效方法.似乎遵循这些标准将允许最终操纵外部引用(如果最终修改了该类),从而在将来为您提供更多选择.这仅仅是样式问题(例如一个真实的括号或匈牙利的命名约定),还是我对此信念有道理?在这种情况下,实际上是否有最佳实践?

(I admit, that many of the above are slightly repetative, but they each seem different enough to merit such treatment... )

It just seems that this is the most efficient means of preventing changing a variable by accident. It also seems like following these standards will allow for the eventual manipulation of external references (if the class is eventually modified), thus leaving you with further options in the future. Is this simply a style issue (like one true bracket or Hungarian naming conventions), or do I have justification in this belief? Is there actually a best practice in this case?

修改
我认为这需要纠正.我在实际使用的上方使用了全局",而不是通过实例方法全局",而不是任何地方,任何地方都可以全局访问".

edit2
要求提供一个示例:

edit
I think this needs to be corrected. I used "globally" above where I actually meant, "globally by instance methods" not "globally accessible by anything, anywhere".

edit2
An example was asked for:

class foo
{
    private $_my_private_variable;

    public function __constructor__()
    {
     }

    public function useFoo( $variable )
    {
        // This is the line I am wondering about,
        // there does not seem to be a need for storing it.
        $this->_my_private_variable = $variable; 
        $this->_doSometing();
    }

    private function _doSomething()
    {

        /*
          do something with $this->_my_private_variable.
        */
        // This is the only place _my_private_variable is used.
        echo $this->_my_private_variable;
    }
}

这是我会做的方式:

class foo
{

    public function __constructor__()
    {
     }

    public function useFoo( $variable )
    {
        $this->_doSometing( $variable );
    }

    private function _doSomething( $passed_variable )
    {
        /*
          do something with the parameter.
        */
        echo $passed_variable;
    }
}

推荐答案

通常,类成员应表示类对象的 state .

In general, class members should represent state of the class object.

它们不是方法参数的临时位置(这就是方法参数的作用).

They are not temporary locations for method parameters (that's what method parameters are for).

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

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