PHP classes why use public keyword?

2020-03-13 06:30发布

Why should I declare class properties (variables) or methods (functions) using the keyword public, if they're public by default? Or, are they?

To phrase my question differently, is public redundant? I understand private and protected, but why declare public if class members are public anyway?

标签: php class public
4条回答
乱世女痞
2楼-- · 2020-03-13 06:39

As of php 5.3 (I think, its been a while), using the var keyword raises E_STRICT errors, so public has to be used to declare object vaiables. As for functions, I believe it is more of a consistency thing.

查看更多
Luminary・发光体
3楼-- · 2020-03-13 06:51

Yes, public is the default (see visibility docs).

People add it, so it is consistent with all the other methods / properties.

Furthermore, if you want to declare a property public and don't want to use public you will need to use var, which is not recommended and will likely be deprecated at some point.

查看更多
够拽才男人
4楼-- · 2020-03-13 06:56

Sure it is redundant since that is the default visibility level. You should avoid them when you can. Some people add the public keyword explicitly so that code is little more readable.

查看更多
5楼-- · 2020-03-13 06:58

There is no technical reason to use public however a visibility keyword is required by PSR-2 on all functions so if you want to follow PSR-2 then you should use it:

4.3. Methods

Visibility MUST be declared on all methods.

https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md#43-methods

查看更多
登录 后发表回答