Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 seen 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

like image 549
Horse Avatar asked Jul 07 '11 16:07

Horse


People also ask

How do I find the instance of an object in PHP?

PHP | get_class() Function Return Value: This function returns the class name of which object is an instance. It returns FALSE if the object is not an object. If the object is omitted when inside the class then the class name is returned. $obj = new GFG();

What does :: class do in PHP?

SomeClass::class will return the fully qualified name of SomeClass including the namespace. This feature was implemented in PHP 5.5. It's very useful for 2 reasons. You can use the use keyword to resolve your class and you don't need to write the full class name.

What is Instanceof an example of in PHP?

The instanceof keyword is used to check if an object belongs to a class. The comparison returns true if the object is an instance of the class, it returns false if it is not.


2 Answers

debug_backtrace() will give the whole shebang what happened. get_class($this) will give the top child class if you need just that.

like image 109
Adrian World Avatar answered Sep 29 '22 19:09

Adrian World


Call in your constructor debug_backtrace or debug_print_backtrace.

like image 30
user703016 Avatar answered Sep 29 '22 20:09

user703016