PHP: friend classes and ungreedy caller function/c

2019-04-02 09:02发布

问题:

Is there any way to get the caller function with something else than debug_backtrace()?

I'm looking for a less greedy way to simulate scopes like friend or internal.

Let's say I have a class A and a class B.

Until now, I've been using debug_backtrace(), which is too greedy (IMHO).

I thought of something like this:

<?php

    class A
    {
        public function __construct(B $callerObj) {}
    }

    class B
    {
        public function someMethod()
        {
            $obj = new A($this);
        }
    }
?>

It might be OK if you want to limit it to one specific class, but let's say I have 300 classes, and I want to limit it to 25 of them?

One way could be using an interface to aggregate:

public function __construct(CallerInterface $callerObj)

But it's still an ugly code.

Moreover, you can't use that trick with static classes.

Have any better idea?

回答1:

You can call debug_backtrace(FALSE), which will then not populate the object index. This will speed it up a little bit, but generally, debug_backtrace is to be avoided in production code, unless your app is software tool where speed is not an issue or when using it for error handling.

From what I understand, you want to

  • have an implicit reference to the caller available in the callee and
  • outside access to private and protected properties to selected classes.

Both does not exist in PHP (and breaks encapsulation imho). For a discussion, please see

  • [PHP-DEV] reference caller object and
  • [PHP-DEV] Support for friend classes


回答2:

PHP really doesn't provide you an elegant way of handling this. Without meaning to start a language flamewar, I'm going to gingerly suggest that your design skills and needs have probably exceeded the limitations of your tool. PHP is a lightweight scripting language that's had a lot of pseudo-OOP features bolted onto it, but at its core, it wasn't ever designed for elegant enterprise architecture.