简体   繁体   English

无论如何在PHP中定义公共或私有或受保护的类

[英]is there anyway to define public or private or protected classes in PHP

Is there anyway to create public or private or protected classes in a namespace just like java? 无论如何,像Java一样在命名空间中创建公共或私有或受保护的类吗?

like... 喜欢...

namespace foo;

public class Account {
  .......
}


private class PrivateAccount {
 .......
}

please let me know if there is any workaround to do this in PHP. 请让我知道在PHP中是否有任何解决方法。

No, classes in PHP may not be anything but public and that is declared implicitly. 不,PHP中的类可能不是公共类,而是隐式声明的。 From the PHP docs on classes in PHP5 : PHP5中有关PHP文档

Basic class definitions begin with the keyword class, followed by a class name, followed by a pair of curly braces which enclose the definitions of the properties and methods belonging to the class. 基本的类定义以关键字class开头,后跟一个类名,然后是一对大括号,其中花括号将属于该类的属性和方法的定义括起来。

Putting a visibility keyword in front of the class will likely result in a fatal error. 将可见性关键字放在班级前面可能会导致致命错误。

Typically what you do is declare the constructor of the class private. 通常,您要做的是将类的构造函数声明为private。 Then you can create a separate static function in the class that will do some checks (ie check the namespace) and conditionally return an instance of the class by calling the private constructor. 然后,您可以在类中创建一个单独的静态函数,该函数将进行一些检查(即检查名称空间),并通过调用私有构造函数有条件地返回该类的实例。 This is also typically how you implement singletons. 通常,这也是实现单例的方式。

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

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