Default visibility of class methods

04/13/2020 00:30:01

I looked at the manual, but I can't seem to find the answer.

What is the default visibility in PHP for methods without a visibility declaration? Does PHP have a package visibility like in Java?

For example, in the following code, is go() public or private?

class test {
  function go() {
  }
}

The reason I asked is that I've seen many constructors code written as function __construct() and some as public function __construct(). Are they equivalent?

Verified Answer (176 Votes)

02/09/2010 00:49:33

Default is public.

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

http://www.php.net/manual/en/language.oop5.visibility.php

176

Answer #2 (22 Votes)

02/09/2010 00:48:26

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.

And no, PHP has no package visibility, mainly because until recently PHP had no packages.

22

Answer #3 (9 Votes)

02/09/2010 00:48:47

The default is public. The reason probably is backwards compatibility as old code expects it to be public (it would stop working if it weren't public).

9
3
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.