PHP:朋友类和不愉快的调用者函数/类 [英] PHP: friend classes and ungreedy caller function/class

查看:113
本文介绍了PHP:朋友类和不愉快的调用者函数/类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了debug_backtrace()以外,还有什么方法可以获取调用方函数?

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

我正在寻找一种不太贪婪的方式来模拟 friend internal 之类的范围.

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

假设我有A类和B类.

直到现在,我一直在使用debug_backtrace(),它太贪婪(IMHO).

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

我想到了这样的东西:

<?php

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

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

如果您想将其限制为一个特定的类,那也许还可以,但假设我有300个类,而我想将其限制为其中的25个?

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)

但是它仍然是一个丑陋的代码.

此外,您不能静态类使用该技巧.

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

有更好的主意吗?

推荐答案

您可以调用debug_backtrace(FALSE),这样将不会填充对象索引.这样可以加快速度,但是通常,在生产代码中应避免使用debug_backtrace,除非您的应用是速度不成问题的软件工具,或者将其用于错误处理时都是如此.

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.

据我了解,您想

  • 在被叫方中有一个对调用方的隐式引用,
  • 对选定类的私有和受保护属性的外部访问.

两者在PHP中都不存在(并破坏了封装恕我直言).有关讨论,请参阅

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

这篇关于PHP:朋友类和不愉快的调用者函数/类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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