首页 > 解决方案 > 如何在 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等不同的类,所有这些类都是convertMethodCurrency类的调用函数。

我需要从它调用convertMethod的位置(哪个类)编写代码?Currency

有没有办法做到这一点?

标签: phpoopmethods

解决方案


一个简单的方法是让调用者告诉你。

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

再说一遍:做正确的事,不要做魔术。


推荐阅读