Home > Article > Backend Development > Why Do Some PHP Class Methods Start with an Underscore?
While exploring PHP libraries, you might have noticed that certain developers prefer to preface their class methods with a lone underscore, like:
public function _foo()
...instead of the more straightforward:
public function foo()
Personal preferences aside, what's the origin of this naming convention?
One theory suggests that it dates back to PHP 4, when the language lacked dedicated mechanisms for marking methods as protected or private. Developers resorted to using an underscore prefix to signify, "Hey, don't call this method from outside the class." This was often accompanied by an additional /*private/ annotation for emphasis:
/**private*/ __foo() {...}
Some speculate that the underscores might serve as a visual cue for custom or extension methods that don't belong to the primary class API. This could help developers identify and distinguish between core and supplemental functionality.
It's also possible that this naming practice was borrowed from another programming language. However, there seems to be no definitive evidence to support this theory.
It's important to note that there is no widespread convention in PHP to prefix all class methods with underscores. The developers you encountered might have their own reasons for doing so, but it's not a recommended or widely adopted practice.
The above is the detailed content of Why Do Some PHP Class Methods Start with an Underscore?. For more information, please follow other related articles on the PHP Chinese website!