Home > Backend Development > PHP Tutorial > Why Do Some PHP Class Methods Have a Leading Underscore?

Why Do Some PHP Class Methods Have a Leading Underscore?

DDD
Release: 2024-11-10 19:15:03
Original
278 people have browsed it

Why Do Some PHP Class Methods Have a Leading Underscore?

What's the deal with a leading underscore in PHP class methods?

PHP developers prefix some class methods with a single underscore, such as _foo(), instead of foo(). While it's ultimately a personal preference, this technique has roots in PHP 4.

Before OOP was introduced in PHP 4, there were no protected or private methods. Developers prefaced methods intended to be with an underscore to discourage external access. The convention is similar to the syntax in other languages. In older classes, developers sometimes annotated methods with /***/ __foo().

It's important to note that not all methods starting with an underscore are meant to be . Over time, some developers may have extended the convention to differentiate between internal and external methods. However, this is not a standard practice and has led to confusion.

In modern PHP, it's best to use the proper visibility modifiers (public, protected, ) to define method accessibility. The presence of a leading underscore alone should not be interpreted as a restriction on method use.

The above is the detailed content of Why Do Some PHP Class Methods Have a Leading 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template