1

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?
Common Man
  • 103
  • 2
  • 13
  • 2
    Unless you want to use the singleton pattern.... just explicitly declare your constructor as public..... simple readability of code matters far more than saving 7 keystrokes when writing your classes. Why is debating this even a thing? – Mark Baker May 05 '17 at 09:58

4 Answers4

3

PSR-2 §4.3 reads:

Visibility MUST be declared on all methods.

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

Alex Blex
  • 34,704
  • 7
  • 48
  • 75
2

__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.

arbogastes
  • 1,308
  • 9
  • 10
0

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.

Shoukat Mirza
  • 800
  • 9
  • 19
0

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

Community
  • 1
  • 1
Calvin
  • 46
  • 7