问题
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?
回答1:
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.
回答2:
The logging you're doing looks like a Reflection kind of logging, rather than an aspect based kind of logging.
You can get really far with Dependency Injection. Adding loggers for the different kinds of things you want to be logging, ie. intrusion-bad-password, mail-log etc.
In my opinion it doesn't make much sense to a Reflection kind of logging, this requires you to expose too much of your internals.
If you just want a stacktrace when errors occur use Exception->getTrace
.
来源:https://stackoverflow.com/questions/16679792/using-magic-constants-from-another-scope