Search code examples
phpcoding-stylenaming-conventionsstandards

Protected properties prefixed with underscores


Like:

public
  $foo        = null,
  $bar        = 10;

protected

  $_stuff     = null,
  $_moreStuff = 5;

A lot of people seem to do this. Why?

Isn't this inconsistent naming (like some PHP functions are :))?


Solution

  • It really comes down to one thing: personal preference.

    I, personally, am also one who uses that naming convention. Prefixing anything that is protected or private with an underscore, be it a variable or a function, lets myself and any other programmer who I regularly work with know that that variable is global and will not be accessible outside of the current class/context.

    An example that helps clarify the use-case would be with class methods:

    class Example {
        public function firstFunction() {
            // do stuff
        }
    
        protected function _secondFunction() {
            // do more stuff
        }
    }
    

    When I'm writing code that uses the class Example, or working inside of the class itself, if I see _secondFunction() I will immediately know that it's not a public function because of the starting _ and thereby not accessible outside of the class; no need to go and find the actual function declaration and see the modifier. On the flip side, I will know that firstFunction() is public because it doesn't begin with one.