无论如何在PHP中定义公共或私有或受保护的类 [英] is there anyway to define public or private or protected classes in PHP

查看:33
本文介绍了无论如何在PHP中定义公共或私有或受保护的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法像 java 一样在命名空间中创建公共或私有或受保护的类?

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

喜欢...

namespace foo;

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


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

请让我知道是否有任何解决方法可以在 PHP 中执行此操作.

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

推荐答案

通常您所做的是将类的构造函数声明为私有.然后,您可以在类中创建一个单独的静态函数,该函数将执行一些检查(即检查命名空间)并通过调用私有构造函数有条件地返回类的实例.这也是您实现单例的典型方式.

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.

这篇关于无论如何在PHP中定义公共或私有或受保护的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆