php find where class is instantiated from
I am having some issues on a large-ish project, and it boils down to a particular class is somehow being instantiated multiple times, which is causing un-needed replication / overheads.
Is there any way to find out automatically what file / line number it is being instantiated from?
I have se开发者_如何学Goen this question here - Find where a class was instantiated but I am not getting a fatal error for it being redeclared so I dont think include / require is the problem.
in the constructor I have got it to output to a txt file with timestamp, just need to know where the offending code is and remove / streamline it
debug_backtrace() will give the whole shebang what happened. get_class($this) will give the top child class if you need just that.
Call in your constructor debug_backtrace
or debug_print_backtrace
.
You can import the project into an IDE and search through there. For example, in Netbeans if you right-click the name of a class and select "Find Usages" you'll get a list of all the calls to the specific class (the same for functions etc).
You could make the class a singleton. Then update any place the class is called to use the singleton pattern. You can also make the __construct() private or protected so that it has to be instantiated using the instance() method. That will mean the class is only called once.
Then for your peace of mind to figure out where it was being called multiple times, you can have the instance() method print out debug information using debug_backtrace.
You could add a parameter to the constructor's declaration. Since the other classes that are calling it haven't been edited for that parameter, there should be errors for each instance it is trying to be instantiated.
For profiling PHP scripts I use the xdebug extension. This together with KCachegrind or WinCacheGrind will allow you to see which classes / functions are calling the class in question.
The following code-snippet is based on the usage of debug_backtrace().
The backtrace is fetched without arguments and options and limited to 3 array items; then the "class" name is returned from the second element of the array.
Demo
Code:
<?php
class MyClass
{
// find out where $myClass->exec() was called
static function getInstantiatingClass()
{
return debug_backtrace(2, 3)[2]['class'];
}
function exec()
{
echo __METHOD__ . ' was called from Class ' . self::getInstantiatingClass();
}
}
class Demo
{
function test()
{
$myClass = new MyClass;
$myClass->exec();
}
}
$demo = new Demo;
$demo->test();
Result:
MyClass::exec was called from Class Demo
精彩评论