php - 如何在 PHP 中调用一个方法/函数的另一个类中获取类名,不包括 debug_backtrace() 方法或 xdebug 方法?
问题描述
我有不同的课程。现在在一堂课中,我有以下方法/功能。
class Currency extends CurrencyClassAbstract {
public function __construct(
}
public function convertMethod($price) {
//need to know here which class is calling this method/function
}
}
现在,有product、tax、cartclass、orderclass等不同的类,所有这些类都是convertMethod
Currency类的调用函数。
我需要从它调用convertMethod
的位置(哪个类)编写代码?Currency
有没有办法做到这一点?
解决方案
一个简单的方法是让调用者告诉你。
public function convertMethod($caller, $price) {
// we know the caller is invoking this method
}
在您的情况下,其他方法(设计模式)并不比这更容易。
好吧,如果你坚持,这里有一些魔法,但也不推荐。
<?php
trait CurrencyCalculator {
function calcCurrency($price) {
echo "calcCurrency in " . get_called_class();
}
}
class Order {
use CurrencyCalculator;
function foo() {
$this->calcCurrency(1.0);
}
}
$o = new Order();
$o->foo();
输出:
calcCurrency in Order
再说一遍:做正确的事,不要做魔术。
推荐阅读
- android - 该软件包似乎已损坏(但通过电报安装)
- reactjs - React:访问触发合成事件的组件
- android - Android:如何使用 mockK 对 Observable concatMap 组合进行单元测试
- javascript - 为什么 powershell 不运行 Angular 命令?
- xamarin - 更新 Nuget 导致异常未处理:System.TypeLoadException
- .net-core - 如何使用 Bot Builder 向第三方服务发出经过身份验证的请求?
- visual-studio - 为什么安装了最新Qt Addin的VS2019没有Qt项目模板?
- python - 将帧上传到云端并通过 python 中的应用程序显示
- swift - iOS13 中的 ContextMenuConfigurationForRowAt
- botframework - 使用 BrowserWebSpeech 在网络聊天中更改语音