限制什么可以创建一个PHP类 [英] Restrict what can create a PHP Class

查看:118
本文介绍了限制什么可以创建一个PHP类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类,A和B。在应用程序逻辑中,没有人被允许创建类B的对象,除了类A。
但是,因为我不想在同一个文件中的两个类,我无法限制它与私人属性。

I got two classes, "A" and "B". In the application logic no one is allowed to create an object of class "B", except for class "A". But, since I dont want to have the two classes in the same file I cant restrict it with the "private" properity.

是否可以创建此类限制?如果别人A尝试创建类B的对象,你说piss off!?

Is it possible to create this kind of restriction? If someone other then "A" tries to create an object of class "B", you say piss off!?

推荐答案

是如同黑客,因为它得到,你不应该使用它。我只发布它,因为我喜欢黑客的事情;)此外,如果启用 E_STRICT 错误报告,则会抛出错误:

This is as hacky as it get's and you should not use it. I only post it, because I like hacky things ;) Furthermore this will throw an error if E_STRICT error reporting is enabled:

class B
{
    private function __construct() {}

    public function getInstance() {
        if (!isset($this) || !$this instanceof A) {
            throw new LogicException('Construction of B from a class other than A is not permitted.');
        }

        return new self;
    }
}

class A
{
    function someMethod() {
        $b = B::getInstance(); // note that I'm calling the non-static method statically!
    }
}

可在本手册页的第二个示例中

The reason why this works is a "feature" which may be seen in the second example of this manual page.

这篇关于限制什么可以创建一个PHP类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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