Default visibility of class methods in PHP
PhpOopVisibilityPhp Problem Overview
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?
Php Solutions
Solution 1 - Php
Default is public.
>Class methods may be defined as public, private, or protected. Methods declared without any explicit visibility keyword are defined as public.
Solution 2 - Php
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.
Solution 3 - Php
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).
Solution 4 - Php
> Default visibility is PUBLIC
Solution 5 - Php
When no visibility keyword (public
,private
or protected
) used, methods will be public. But, you cannot define properties in this way. For properties, you will need to append a visibility keyword on declaration.
For properties which is not declared in the class and you assign a value to it inside a method will have a public visibility.
<?php
class Example {
public $name;
public function __construct() {
$this -> age = 9; // age is now public
$this -> privateFunction();
}
private function privateFunction() {
$this -> country = "USA"; // this is also public
}
}
Solution 6 - Php
function __construct()
and public function __construct()
works as same method name.
If you could not define the prefix for a method name, it should be by default public.