Pre-declare all private/local variables?

后端 未结 4 1058
我寻月下人不归
我寻月下人不归 2020-11-27 06:31

This may be a basic question, but it has kept me wondering for quite some time now.

Should I declare all private/local variables being private? Or is this only neces

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 07:20

    It's generally a good rule of thumb for variables to define and initialize them before use. That includes not only definition and initial value but also validation and filtering of input values so that all pre-conditions a chunk of code is based on are established before the concrete processing of the data those variables contain.

    Same naturally applies to object members (properties) as those are the variables of the whole object. So they should be defined in the class already (by default their value is NULL in PHP). Dynamic values / filtering can be done in the constructor and/or setter methods.

    The rule for visibility is similar to any rule in code: as little as necessary (the easy rule that is so hard to achieve). So keep things local, then private - depending if it's a function variable or an object property.

    And perhaps keep in the back of your mind that in PHP you can access private properties from within the same class - not only the same object. This can be useful to know because it allows you to keep things private a little bit longer.

    For instance, I have the (temporary) result of a calculation. Should I pre-declare this variable?

    This is normally a local variable in a function or method. It's defined when it receives the return value of the calculation method. So there is no need to pre-declare it (per-se).

    ...
    
    function hasCalculation() {
        $temp = $this->calculate();
        return (bool) $temp;
    }
    
    ...
    

    If the calculation is/was expensive it may make sense to store (cache) the value. That works easily when you encapsulate that, for example within an object. In that case you'll use a private property to store that value once calculated.

    Take these rule with a grain of salt, they are for general orientation, you can easily modify from that, so this is open to extend, so a good way to keep things flexible.

提交回复
热议问题