PHP:友元类和不贪婪的调用者函数/类
除了 debug_backtrace() 之外,还有什么方法可以获取调用者函数吗?
我正在寻找一种不太贪婪的方法来模拟诸如 friend 或 internal 之类的范围。
假设我有一个 A 类和一个 B 类。
到目前为止,我一直在使用 debug_backtrace()
,这太贪婪了(恕我直言)。
我想到了这样的事情:
<?php
class A
{
public function __construct(B $callerObj) {}
}
class B
{
public function someMethod()
{
$obj = new A($this);
}
}
?>
如果你想将其限制为一个特定的类可能没问题,但假设我有 300 个类,我想将其限制为其中 25 个?
一种方法是使用接口进行聚合:
public function __construct(CallerInterface $callerObj)
但这仍然是一个丑陋的代码。
此外,您不能在静态类中使用该技巧。
有更好的主意吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
PHP 确实没有提供一种优雅的方式来处理这个问题。无意引发语言大战,我将小心翼翼地建议您的设计技能和需求可能已经超出了您的工具的限制。 PHP 是一种轻量级脚本语言,附加了许多伪 OOP 功能,但其核心并不是为优雅的企业架构而设计的。
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.
您可以调用
debug_backtrace(FALSE)
,这将不会填充对象索引。这会稍微加快速度,但通常情况下,在生产代码中应避免使用 debug_backtrace,除非您的应用程序是速度不是问题的软件工具,或者使用它进行错误处理。据我了解,您希望
两者在 PHP 中都不存在(并且破坏了封装(恕我直言))。有关讨论,请参阅
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
Both does not exist in PHP (and breaks encapsulation imho). For a discussion, please see