user5741640
user5741640

Reputation:

How to get the object that calls a function in PHP?

PHP provides the function get_class(), which does not require a parameter, if it is called in a class context.

I want to write a similar function that is able to retrieve the calling object without explicitly passing it. I tried using debug_backtrace(), but index object is not set:

function outer_function() {
    var_dump(debug_backtrace());
}

class ExampleObject {
    function __construct() {
        outer_function();
    }
}

new ExampleObject();

eval on 3v4l.org

Please note that it's not relevant wether the function is called from the constructor or not; get_class() works also, if it is being called within the constructor.

Upvotes: 1

Views: 229

Answers (2)

sevavietl
sevavietl

Reputation: 3792

You can try the following:

function get_caller(): ?object
{
    foreach (debug_backtrace() as $call) {
        if (isset($call['object'])) {
            return $call['object'];
        }
    }

    return null;
}

Here is the demo.

Upvotes: 3

ArtisticPhoenix
ArtisticPhoenix

Reputation: 21681

Something like this

 public function trace($offset = 0)
 {
    $trace = debug_backtrace(false);
    foreach ($trace as $t) {
        // print_r($t);
        // print_r($offset);
        if ($t['file'] != __FILE__) {
            break;
        }

        ++$offset;
    }
    $arr = array_slice($trace, ($offset - count($trace)));
    return $arr;
}

This is from a debugging package I wrote,

https://github.com/ArtisticPhoenix/Debug

Or you can get it with composer

evo/debug

This part just returns the piece of the back trace from where it was called.

It works as long as the call is no in the same file.

Upvotes: 0

Related Questions