Search code examples
phpclassstaticmagic-methods

Using magic constants from another scope


I created a class Debug in which all properties and methods are static. Using late static binding I use this class as a logger of what is being done and at which moment (in fact I'm testing now performance issue, so I would like to now what and when goes).

So at the moment I have something in each main method of each class like Debug::log(__CLASS__ . '::' . __METHOD__);. In Debug::log() method I can add time and store it in some array.

If I'd wanted some day to change behaviour I would need to change lots of code in many files...

My question is: is it possible somehow to omit these __CLASS__ . '::' . __METHOD__ and the Debug::log() method would know from which class and from which method it was called?

A call stack perhaps?


Solution

  • The function you are looking for is debug_backtrace(); it will give you a data structure you can use for this purpose. There is no way to make the magic constants work that way, although I agree with the idea and you might consider posting a feature requests to allow magic constants used as default values in function definitions to be evaluated at call time, not define time. I would support such a feature request.