Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bwrigley's avatar

Capture the calling file and line number that called my function

I have a helper I've created for managing pretty error messages back to the users while logging useful info for the developers.

However it would be really nice to be able to capture the calling file and line number.

I know I can use the __FILE__ and __LINE__ constants to pass into my function and log that way, but it would be really nice if I could capture them, without having to pass them in every time.

0 likes
3 replies
jlrdw's avatar
jlrdw
Best Answer
Level 75

You might look at stacktrace, I did similar a while back to get a calling class name, adapt as needed:

<?php

namespace App\Helpers;

class DBS
{

    public static function __callStatic($method, $params)
    {
        $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
        
        if (isset($trace[1]['class'])) {
            $class = $trace[1]['class'];
            $slh = strrpos($class, "\") + 1;
        } else {
            return null;
        }
        $model = "\App\Models\SMVC" . "\" . substr($class, $slh, -10) . "Model";
        $instance = new $model();

        return call_user_func_array(array($instance, $method), $params);
    }


}
1 like
bwrigley's avatar

Thanks, I thought this might be more of a php question than a Laravel one. I just wondered if they had a handy package.

Please or to participate in this conversation.