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

不问归期 提交于 2019-12-11 02:41:58

问题


Is there anyway to create public or private or protected classes in a namespace just like java?

like...

namespace foo;

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


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

please let me know if there is any workaround to do this in PHP.


回答1:


Typically what you do is declare the constructor of the class private. Then you can create a separate static function in the class that will do some checks (i.e. check the namespace) and conditionally return an instance of the class by calling the private constructor. This is also typically how you implement singletons.




回答2:


No, classes in PHP may not be anything but public and that is declared implicitly. From the PHP docs on classes in PHP5:

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.

Putting a visibility keyword in front of the class will likely result in a fatal error.



来源:https://stackoverflow.com/questions/9192154/is-there-anyway-to-define-public-or-private-or-protected-classes-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!