Home > Backend Development > PHP Tutorial > Why Do Some PHP Class Methods Start with an Underscore?

Why Do Some PHP Class Methods Start with an Underscore?

Barbara Streisand
Release: 2024-11-09 18:32:02
Original
874 people have browsed it

Why Do Some PHP Class Methods Start with an Underscore?

Why Do Some PHP Class Methods Begin 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()
Copy after login

...instead of the more straightforward:

public function foo()
Copy after login

Personal preferences aside, what's the origin of this naming convention?

Historical Roots in PHP 4

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() {...}
Copy after login

Custom or Extensibility?

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.

Language Influences?

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.

A Refrain from Underscores

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template