简体   繁体   English

__constructor的类中的函数声明,在PHP中没有关键字public

[英]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. 经过长时间的搜索,在PHP类的__constructor函数中使用关键字public ,我并没有获得更好的清晰度。

  1. People saying __constructor itself is public by default. 人们说__constructor本身默认是公开的。 So I don't have to use mention as public . 因此,我不必public提及。
  2. Will there be no change if I mention or don't as public in public function __constructor in PHP? 如果我在PHP的public function __constructor中提到或不public ,会不会有任何变化?
  3. what is the best practice of declaring a __constructor in PHP? 在PHP中声明__constructor的最佳实践是什么? with or without the keyword public ? 有没有关键字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 ? 如果我在public function __constructor不提及关键字public in-front,我将面临哪些不利条件或问题?

PSR-2 §4.3 reads: PSR-2§4.3内容如下:

Visibility MUST be declared on all methods. 必须在所有方法上声明可见性。

__constructor is one of "all methods", so the rule applies. __constructor是“所有方法”之一,因此该规则适用。

__constructor is a method. __constructor是一种方法。 Visibility of methods is described in PHP Doc as: 方法的可见性在PHP Doc中描述为:

Class methods may be defined as public, private, or protected. 类方法可以定义为公共,私有或受保护的方法。 Methods declared without any explicit visibility keyword are defined as public. 声明时没有任何显式可见性关键字的方法被定义为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. 始终包含它是一个好习惯,但是PHP4支持的类没有访问修饰符,因此常见的是在遗留代码中不使用它们。

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 查看https://stackoverflow.com/a/455929/7423021了解更多详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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