Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP classes why use public keyword?

Tags:

php

public

class

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?

like image 441
Ben Avatar asked Jan 13 '11 07:01

Ben


2 Answers

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.

like image 189
NikiC Avatar answered Oct 04 '22 19:10

NikiC


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.

like image 38
Travis Avatar answered Oct 04 '22 21:10

Travis