限制可以创建PHP类的内容

Emi*_*mil 7 php class restriction

我有两个班,"A"和"B".在应用程序逻辑中,除了类"A"之外,不允许任何人创建类"B"的对象.但是,因为我不想在同一个文件中使用这两个类,所以我不能用"私有"特性来限制它.

是否有可能制造这种限制?如果其他人然后"A"试图创建类"B"的对象,你说小便!?

Nik*_*kiC 7

这就像它得到的那样hacky,你不应该使用它.我只发布它,因为我喜欢hacky的东西;)此外,如果E_STRICT启用了错误报告,这将引发错误:

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!
    }
}
Run Code Online (Sandbox Code Playgroud)

其工作原因是"功能",可以在本手册页的第二个示例中看到.


Nev*_*kes 5

你可以检查回溯:

class B
{
    public function __construct()
    {
        $chain = debug_backtrace();
        $caller = $chain[1]['class'];

        if ('A' != $caller) {
            throw new Exception('Illegal instantiation');
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你走这条路,你应该分析它的表现.由于某种原因,该函数被称为**debug**_backtrace. (4认同)
  • 哦,超过同意戈登,但这是一个解决方案! (2认同)

MAN*_*UCK 0

在B的构造函数中,要求传入A。当你想从A中获取B时,只需创建一个B并传入A即可。当调用new B时,将要求传入A。

class A
{
    private $b;

    private function getB()
    {
        if (null === $this->b)
        {
            $this->b    = new B($this);
        }

        return $this->b;
    }
}

class B
{
    public function __construct(A $a)
    {

    }
}
Run Code Online (Sandbox Code Playgroud)