简体   繁体   中英

function declaration in a class for __constructor without the keyword public in PHP

I haven't got a better clarity after a long search about, using keyword public in a __constructor function in a PHP class.

  1. People saying __constructor itself is public by default. So I don't have to use mention as public .
  2. Will there be no change if I mention or don't as public in public function __constructor in PHP?
  3. what is the best practice of declaring a __constructor in PHP? with or without the keyword public ?
  4. what are the disadvantages or issues that I will face if I don't mention the keyword public in-front of a public function __constructor ?

PSR-2 §4.3 reads:

Visibility MUST be declared on all methods.

__constructor is one of "all methods", so the rule applies.

__constructor is a method. Visibility of methods is described in PHP Doc as:

Class methods may be defined as public, private, or protected. Methods declared without any explicit visibility keyword are defined as public.

So there is no need to write 'public' visibility for public methods.

But still I prefer to write explicitly visibilities (even 'public') for methods - code is more obvious for everyone.

Default is public. It's a good practice to always include it, however PHP4 supported classes without access modifiers, so it's common to see no usage of them in legacy code.

Since nobody mentions it.

function __constructor ()

Is a function that will run when the class is made. Check https://stackoverflow.com/a/455929/7423021 for bigger details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM