-2

I'm having different classes. Now in one class, I'm having the following method/function.

class Currency extends CurrencyClassAbstract {

    public function __construct(

    }   
    public function convertMethod($price) {

        //need to know here which class is calling this method/function

    }

}

Now, there are different classes like product, tax, cartclass, orderclass all these classes are calling convertMethod function of Currency class.

I need to write code in convertMethod of Currency from where (which class) it is calling?

Is there any possible way to do this?

sandip
  • 533
  • 9
  • 29
  • FWIW, your `convertMethod` should *not behave differently* depending on where it's called from. If anything, you should only use this information for logging debug traces, nothing more. Is that what this is about? What information are you *really* trying to figure out? – deceze Sep 26 '18 at 07:59
  • This may help you [ https://stackoverflow.com/questions/1214043/find-out-which-class-called-a-method-in-another-class ] – Chayan Sep 26 '18 at 08:02
  • @Chayan your method is not practical, it's very slow, it is not for release/production usage. – shawn Sep 26 '18 at 08:04
  • *"Excluding [the only viable options]…"* – Well, then, *no*. Pass an additional parameter to your function if you need that information. – deceze Sep 26 '18 at 08:06
  • Do the right thing. Do not rely on tricks. – shawn Sep 26 '18 at 08:10

1 Answers1

-1

A simple approach is to let the caller tell you.

public function convertMethod($caller, $price) {
    // we know the caller is invoking this method

}

Other methods (design patterns) are not easier than this one in your case.

Well, if you insist to, here is some magic but not recommended either.

<?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();

Output:

calcCurrency in Order

Again: do the right thing, do not do magic.

shawn
  • 4,305
  • 1
  • 17
  • 25