PHP 中类方法的默认可见性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2224380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Default visibility of class methods in PHP
提问by Yada
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?
PHP 中没有可见性声明的方法的默认可见性是多少?PHP 是否具有像 Java 中那样的包可见性?
For example, in the following code, is go()public or private?
比如下面的代码,是go()public还是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?
我问的原因是我见过许多构造函数代码编写function __construct()为public function __construct(). 它们是等价的吗?
回答by Jansen Price
Default is public.
默认是公开的。
Class methods may be defined as public, private, or protected. Methods declared without any explicit visibility keyword are defined as public.
类方法可以定义为 public、private 或 protected。没有任何显式可见性关键字声明的方法被定义为公共。
回答by Johnco
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.
默认是公开的。始终包含它是一个很好的做法,但是 PHP4 支持没有访问修饰符的类,因此在遗留代码中看不到它们的使用是很常见的。
And no, PHP has no package visibility, mainly because until recently PHP had no packages.
不,PHP 没有包可见性,主要是因为直到最近 PHP 还没有包。
回答by Tomas Markauskas
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).
默认是公开的。原因可能是向后兼容,因为旧代码希望它是公开的(如果它不是公开的,它将停止工作)。
回答by James.Valon
When no visibilitykeyword (public,privateor 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.
当未使用可见性关键字(public,private或protected)时,方法将为public。但是,您不能以这种方式定义属性。对于properties,您需要在声明时附加一个可见性关键字。
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
}
}
回答by Gazi Anis
function __construct()and public function __construct()works as same method name.
function __construct()并public function __construct()以相同的方法名称工作。
If you could not define the prefix for a method name, it should be by default public.
如果您无法为方法名称定义前缀,则默认情况下它应该是 public。

