Best to use Private methods or Protected methods?

后端 未结 10 2325
[愿得一人]
[愿得一人] 2020-12-03 09:52

In a lot of my PHP projects, I end up with classes that have non-public functions that I don\'t intend to extend.

Is it best to declare these as protected, or privat

10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-03 10:38

    I generally use private in some very specific occasion where the method/variable is very internal and shouldn't be read or write by any other subclass (so basically almost never). The only case in mind where I use private variable is for exemple :

    final public function init():void
    {
        if(!_initialized)
        {
            _init();
            _initialized = true;
        }
    
    }
    
    protected function _init():void
    {
        // specific code.
    }
    

    In most of the other case the methods and variable should be useful for inheritance at least as a reading function. Because most of the time when I use code made by someone else, and when this code use private things it always and with a lot of trouble :

    • the wanted behavior is not already implement or complete

    • I can't use a method because it's private

    • I can't change this method because it's private

    • if it's protected (or if I change it as protected) then I can't rework the code (aka adding behaviors in between tow others instruction, because part of this code use private methods or variables...

      = at the ends you almost change all the accessor to protected to get the ability of extending the class!

    Thus, if you think this class could be extends prefer protected for everything except very specific case (if you think a specific method should only be used but not changed use final protected).

    If you think this class shouldn't be extended in any case : use private.

提交回复
热议问题