Reputation: 745
Going through other people's source code, I've noticed some people specifically define public functions as public
in their classes. I know that class variables need that definition, but PHP states that defining visiblity for methods is optional, [Class methods may be defined as public, private, or protected. Methods declared without any explicit visibility keyword are defined as public.
].
Is there any benefit from specifically defining a function as public instead of letting PHP assume it's public?
Upvotes: 3
Views: 53
Reputation: 33196
There is no programmatic advantage to defining the public visibility of a property or method.
But there are great advantages in terms of code styling. A beginner in php might not know that functions are public by default. Also it makes sense to always add visibility to functions, otherwise you have different code styles for private/protected functions and public functions.
This is even taken into account for psr-2
, which forces you to add visibility to all methods and properties.
Upvotes: 1
Reputation: 1154
Not everyone knows what the default visibility for a given language feature is. For example, in C++, structs and classes are essentially the same, where struct members and public by default and classes are private by default - that doesn't stop people from specifying what they are.
By explicitly stating the visibility of the given feature, there is no confusion about it. This is allows people to read and digest code more quickly and is especially helpful to those who aren't familiar with the default visibility.
Upvotes: 1